【问题标题】:trouble reading excel file c #读取excel文件c#的麻烦
【发布时间】:2016-07-19 17:39:48
【问题描述】:

大家早上好。 我有很多 excel 文件。 这很奇怪,但我看不懂。如果我将内容复制到新的 excel 电子表格中,则一切正常。 我想避免在阅读之前进行所有转换。我尝试了所有常规方式的“扩展属性”,但我总是犯同样的错误:“外部表不是预期的格式。”可能这些文件是在 Excel 97 中创建的。但是使用正确的外部方法不起作用。 你能给我支持吗?谢谢你,美好的一天

在这里我尝试使用扩展属性 Excel 8.0,但我已经全部尝试过了。

string connstr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + PercorsoCompletoFileExcel + ";Extended Properties='Excel 8.0;HDR=Yes;'";

在这里,我通过一个选择只取某些列。如果我将文件复制到新的 Excel 工作表,我会重复所有工作,但我希望它可以与原始文件一起使用

strSQL = "SELECT [NumeroContratto] AS [Numero contratto],[Codice Cliente] as [Codice cliente],[Importo Tessera] as [Importo Tessera],[Costo contratto] as [Costo contratto],Spese,Commissioni,[Importo Servizi] as [Servizi],[Importo Sconto] as [Sconto],[Importo Addebito Totale] as [Totale]  from [" + foglio + "] where [Importo Addebito Totale] is not null";
            OleDbCommand cmd = new OleDbCommand(strSQL, conn);
            DataSet ds = new DataSet();
            OleDbDataAdapter da = new OleDbDataAdapter(cmd);
            da.Fill(ds);

【问题讨论】:

    标签: c# excel frameworks .net-3.5 excel-2007


    【解决方案1】:

    以下代码适用于我的情况。

    根据我的经验,您需要先将上传的文件保存在应用程序目录中。如果不是读取(.xlsx)文件时会抛出错误。

    对 (.xls) 和 (.xlsx) 文件使用不同的连接字符串。

    string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
    string Extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
    //This setting get from configuration file 
    string FolderPath =ConfigurationManager.AppSettings("UploadFolder").ToString();
    string FilePath = Server.MapPath(FolderPath + "\\" + FileName);
    //Save file  
    FileUpload1.SaveAs(FilePath);
    string conStr = "";
    switch (Extension)
    {
       case ".xls": //Excel 97-03
                    conStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0;";
                    break;
       case ".xlsx": //Excel 07
                    conStr = "Provider=Microsoft.ACE.OLEDB.12.0 ;Data Source={0};Extended Properties=\"Excel 12.0 Xml;IMEX=1;HDR=NO\";";
    
                    break;
            }
           conStr = String.Format(conStr, FilePath);
    

    在配置文件中设置(在我的例子中是“Web.config”,因为它是 Web 应用程序)

    <appSettings>
    <add key="UploadFolder" value="UploadedFilesFolder" />
    </appSettings>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-17
      • 1970-01-01
      • 2013-05-24
      • 2016-05-10
      • 1970-01-01
      • 2011-05-24
      • 1970-01-01
      相关资源
      最近更新 更多