C#读取excel文件时,报“外部表不是预期的格式” 您所在的位置:网站首页 word中web视图文件格式与浏览器中所显示的格式一样 C#读取excel文件时,报“外部表不是预期的格式”

C#读取excel文件时,报“外部表不是预期的格式”

2024-04-08 03:23| 来源: 网络整理| 查看: 265

记录

读取Excel文件时报错

比较全面的问题汇总:转自https://blog.csdn.net/question00/article/details/51445663

最后发现我的excel文件的格式不是标准的Excel格式,能用记事本打开并且不是乱码,所以网上通用的读取Excel文件的办法都不行,例如:OleDB,NOPI,但是文件单独另存为.xls,.xlsx文件后用这些方法可以读取。显然,读取大量文件时不能这样操作。

按照链接里博主的代码“xml转换为excel标准格式”失败。

最后解决:将文件复制到一个临时文件夹,更改文件后缀名为txt,用读txt的办法去读取这个excel文件。我是txt读取到DataTable里面,这个网上就有很多办法了。

附上改文件后缀的代码:

/// /// 更改文件后缀名 /// /// 文件夹路径 /// 源文件后缀名 /// 需要的后缀名 public void ChangeFileType(string path, string sourcefileformat, string newfileformat) { try { DirectoryInfo mydir = new DirectoryInfo(path); FileInfo[] fileInfo = mydir.GetFiles(); //遍历文件夹里的文件 foreach (FileSystemInfo fsi in mydir.GetFileSystemInfos()) { if (fsi is FileInfo) { FileInfo fi = (FileInfo)fsi; if (fi.Extension.ToUpper() == $".{sourcefileformat.ToUpper()}") { fi.MoveTo(Path.ChangeExtension(fi.FullName, newfileformat)); //更改文件类型为txt } } } } catch { throw; } } //调用 //ChangeFileType("D:\temp", "xls", "txt");

萌新,这个问题卡了好久,记录一下。

更新:还是犯蠢了,不是excel的格式,检查了是csv格式,可以直接用读写csv文件的方式读写该文件,上面改文件格式的方法会经常出现该文件被占用的提示。

/// /// 写入csv /// /// 写入内容 public static void WriteCsv(string result) { string fileName = "D:\\新建文件夹\\2023-1-1.csv";//文件路径 string path = Path.GetDirectoryName(fileName); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } if (!File.Exists(fileName)) { StreamWriter sw = new StreamWriter(fileName, true, Encoding.UTF8); string str1 = "条码" + "," + "时间" + "," + "结果" + "\t\n"; //Header,可自己随意创建,以逗号隔开是为了在excel里面打开时是一个个单元格的形式 sw.Write(str1); sw.Close(); } StreamWriter swl = new StreamWriter(fileName, true, Encoding.UTF8); string str = "20230101" + "," + "2023-01-01" + "," + "PASS" + "\t\n"; //string str = $"{result}\t\n" ; swl.Write(str); swl.Close(); } /// /// 读取csv /// /// 完整路径 /// 引入一个数据列表 public static void ReadCsv(string path, out List data) { StreamReader sr; data = new List(); try { using (sr = new StreamReader(path, Encoding.GetEncoding("GB2312"))) { string str = ""; while ((str = sr.ReadLine()) != null) { data.Add(str); } } } catch (Exception ex) { foreach (Process process in Process.GetProcesses()) { if (process.ProcessName.ToUpper().Equals("EXCEL")) process.Kill(); } GC.Collect(); Thread.Sleep(10); Console.WriteLine(ex.StackTrace); using (sr = new StreamReader(path, Encoding.GetEncoding("GB2312"))) { string str = ""; while ((str = sr.ReadLine()) != null) { data.Add(str); } } } }



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有