c# - 将ibfs(从网站下载的Excel文件)文件转换为.xls/.xlsx文件格式,而无需使用C#Asp.net Web应用程序安装Office

标签 c# asp.net excel oledb epplus

我有一个需要格式化来自不同资源的输入文件的要求。我的应用程序通过文件上传接收输入(xls / xlsx / ibfs)文件,并执行条件检查并生成.xlsx文件格式的格式化输出。我所有的输入文件都是由不同的在线公共数据报告网站生成的报告。当我以excel格式下载时,某些网站正在以“ WFServlet.ibfs”文件格式生成。

这不是重复的帖子。我尝试了不同的方法并遵循了这里的建议,并尝试了几种方法,但并没有解决我的问题。抱歉,很长的帖子。我想请年长者建议或帮助解决这个问题。

我可以使用C#OLEDB ACE引擎处理xls和xlsx文件格式。在我的本地计算机和本地托管的IIS服务器中,它都能正常运行。但是,当我上传.ibfs文件格式时,出现了问题。

样本输入

enter image description here

在这里,我发布了我最有效的两种方法:

方法1(使用Microsoft Office Interop)
方法2(使用第三方EPPlus库)

1.方法1(使用Microsoft Office Interop):

在这种方法中,我使用了Microsoft Interop dll。最初在转换之前,我将.ibfs的扩展名更改为.xls,然后使用Microsoft Interop将xls转换为xlsx文件格式。用这种方法,它可以在我的本地机器上正常工作。但这在我的本地IIS服务器中不起作用(在我的本地IIS服务器中,我可以将扩展名从.ibfs更改为.xls,但此后它不会从xls创建xlsx文件)。我将Office12的dll“ Microsoft.Office.Interop.Excel.dll”和“ Office.dll”添加到了项目参考中。

但是用这种方法,我将来可能会遇到问题。目前Office已安装在我的本地计算机上,但是当我们将代码移到服务器上时,我们没有安装Office,客户端也不想在服务器上安装Office。我不确定它是否可以在不安装Office的情况下在具有相同dll的服务器中工作。

下面是代码:

步骤1:如果用户上传的文件是.ibfs文件类型,则将扩展名从.ibs更改为.xls并调用转换方法

 string path ="C:\\testinput\\";
     string extension = Path.GetExtension(InputFile.FileName); // get the extension of user upload file 
     string fileName = "testFile"+ extension; // make a new name to assign to the user uplaoded file
     InputFile.SaveAs(path + fileName); // save the user uploaded file into the testinput folder with testFile file name
     inputFileWithPath = path + fileName; // copy the path of saved file "C:\\testinput\\testFile+extenstion"
     newPath = inputFileWithPath; // used if input file is of .ibfs or .xls extn
     if (extension.Equals(".IBFS") || extension.Equals(".ibfs"))
     {
     //input user uploaded file extension is .ibfs , If file already exist in the upload folder path then delete the old one before File.Move
         if (File.Exists(newPath + ".ibfs"))
             {
             File.Delete(newPath);
             }
             else
             {
             newPath = Path.ChangeExtension(inputFileWithPath, ".xls"); // chnage the file extension from .ibfs to .xls 
             File.Move(inputFileWithPath, newPath); // move the new file .xls to testinput path 
             inputFileWithPath = excelComm.convertExel(newPath); // convert the .xls file into .xlsx file format
             }
     }


步骤2现在使用Interop将逻辑从.xls转换为xlsx

public string convertExel(string FilePath)
    {
       string path = "";
       var app = new Microsoft.Office.Interop.Excel.Application();
       try
        {
        if (File.Exists(FilePath + "x"))  // check if file with .xlsx is already exist, if exist delete it
         { File.Delete(FilePath + "x"); }
        else
        {
        var wb = app.Workbooks.Open(FilePath);
        wb.SaveAs(Filename: FilePath + "x", FileFormat: Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook);
        path = FilePath + "x";
        wb.Close();
        }
        } // end of try
        catch (Exception ex)
         {
         string errorMsg = "";
         CatchException(ex, errorMsg);
         }
        return path;
    }


2.方法2(使用第三方EPPlus库):
我下载了EPPlus.dll,并将其添加到我的项目参考中。我用下面的代码。这基本上将.ibfs的扩展名更改为xls并调用convertExcel方法,在该方法中,它将xls从该数据集转换为数据集,然后将数据表复制到工作簿工作表中,并将其保存为.xlsx文件。但这是行不通的。

下面是代码示例

步骤1:如果用户上传的文件是.ibfs文件类型,则将扩展名从.ibs更改为.xls并调用转换方法

步骤1与上述方法1中所述相同。

步骤2:使用EPPlus库将.xls转换为xlsx。为此,我遵循了C# - convert xls file to xlsx without office components的解决方案

public string convertExel(string FilePath)
  {
   string path = "";
    try
    {
    if (File.Exists(FilePath + "x"))// check if file with .xlsx is already exist, if exist delete it
    {File.Delete(FilePath + "x");}
    else
   {
    string fileName = Path.GetFileNameWithoutExtension(FilePath);
    string filePathXlsx = "C:\\testinput\\"+ fileName + ".xlsx ";
    using (ExcelPackage epackage = new ExcelPackage())
    {
    ExcelWorksheet excel = epackage.Workbook.Worksheets.Add("Sheet1");
    DataSet ds = ReadExcelFile(FilePath); // Causing Error HERE
    DataTable dtbl = ds.Tables[0];
    excel.Cells["A1"].LoadFromDataTable(dtbl, true);
    System.IO.FileInfo file = new System.IO.FileInfo(filePathXlsx);
    epackage.SaveAs(file);
    path = filePathXlsx;
    } // end of using
    }// end of else
    }//end of try
    catch (Exception ex)
    {
    string errorMsg = "";
    CatchException(ex, errorMsg);
    }
    return path;
    } // end of method


//从excel文件生成数据集

   private static DataSet ReadExcelFile(string FilePath)
  {
    string constr = "";
    DataSet ds = new DataSet();
    string extension = Path.GetExtension(FilePath);
    if (extension.Equals(".xls", StringComparison.CurrentCultureIgnoreCase))//Checking for the extentions, if XLS connect using ACE OleDB
            {
                constr = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + FilePath + ";Extended Properties=\"Excel 8.0;IMEX=1;HDR=YES\"";
            }
            //Use ACE OleDb if xlsx extention
            else if (extension.Equals(".xlsx", StringComparison.CurrentCultureIgnoreCase))
            {
                constr = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0;IMEX=1;HDR=YES\"", FilePath);
            }
            else
            {
                constr = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + FilePath + ";Extended Properties=\"Excel 8.0;IMEX=1;HDR=YES\"";
            }

    using (OleDbConnection conn = new OleDbConnection(constr))
      {
       conn.Open(); // causing error HERE
       OleDbCommand cmd = new OleDbCommand();
       cmd.Connection = conn;
       DataTable dtSheet = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });  // Get all Sheets in Excel File
       foreach (DataRow dr in dtSheet.Rows) // Loop through all Sheets to get data
        {
         string sheetName = dr["TABLE_NAME"].ToString();
         cmd.CommandText = "SELECT * FROM [" + sheetName + "]"; // Get all rows from the Sheet
         DataTable dt = new DataTable();
         dt.TableName = sheetName;
         OleDbDataAdapter da = new OleDbDataAdapter(cmd);
         da.Fill(dt);
         ds.Tables.Add(dt);
         } // end of for

        cmd = null;
        conn.Close();
        } // end of using

      return ds;
   }


它给我错误“ System.Data.OleDb.OleDbException(0x80004005):外部表的格式不正确。
       在System.Data.OleDb.OleDbConnectionInternal..ctor(OleDbConnectionString构造,OleDbConnection连接)”

它将扩展名从.ibfs更改为xls,但此后不生成任何xlsx文件。我尝试使用不同的连接字符串,ACE,Xml格式的Jet引擎,HTML导入,单引号和双引号,但没有任何效果。 OLEDB不支持的任何特定格式的已下载Web excel文件是否存在问题?我不确定如何处理此类特定格式。

如果有人能给我任何办法解决“ ibfs”文件格式的问题,我将不胜感激。

我的最新更新:我尝试使用Spire.XLS,但不适用于'.ibfs'文件格式。它只适用于xls和xlsx格式。

仅一个请求,请仅建议使用开源dll。我无法在客户端计算机(服务器)上安装任何软件。我只有使用EPPlus之类的开源库或仅由dll支持的任何东西的选项,而无需进行任何安装。谢谢。

最佳答案

尝试在Extended Properties=\"Excel 12.0;IMEX=1;HDR=YES\"中替换Extended Properties=\"Excel 12.0 Xml;IMEX=1;HDR=YES\"

//Use ACE OleDb if xlsx extention
        else if (extension.Equals(".xlsx", StringComparison.CurrentCultureIgnoreCase))
        {
            constr = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0;IMEX=1;HDR=YES\"", FilePath);
        }

关于c# - 将ibfs(从网站下载的Excel文件)文件转换为.xls/.xlsx文件格式,而无需使用C#Asp.net Web应用程序安装Office,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37446300/

相关文章:

c# - 将变量读入 GridView asp.net 4 c# 中 TemplateField 中的 NavigateUrl

c# - Controller 中的 Controller ?

python - 使用 Python 自动从 ASPX 网站下载文件

c# - 使用 EPPlus 将 PrintArea 设置为 "Print Entire Workbook"

excel - 使用变量(不是单元格值)分配单元格编号

c# - 如何在 PowerShell 脚本中使用 NuGet 包?

c# - ListBox 鼠标悬停时的 ListBoxItem 索引

asp.net - 虚拟目录未配置为 IIS 中的应用程序

javascript - 阻止用户输入美元符号 ($)

excel - 如何将 "conditional formatting>Icon sets"中的图标添加到单个单元格?