簡體   English   中英

將ibfs(從網站下載的Excel文件)文件轉換為.xls / .xlsx文件格式,而無需使用C#Asp.net Web應用程序安裝Office

[英]Converting ibfs (Downloaded Excel files from websites) files to .xls/.xlsx file format without installing Office using C# Asp.net Web application

我有一個需要格式化來自不同資源的輸入文件的要求。 我的應用程序通過文件上傳接收輸入(xls / xlsx / ibfs )文件,並執行條件檢查並生成.xlsx文件格式的格式化輸出。 我所有的輸入文件都是由不同的在線公共數據報告網站生成的報告。 當我以excel格式下載時,某些網站正在以“ WFServlet.ibfs”文件格式生成。

這不是重復的帖子。 我嘗試了不同的方法並遵循了這里的建議,並嘗試了幾種方法,但並沒有解決我的問題。 抱歉,很長的帖子。 我想請年長者建議或幫助解決這個問題。

我可以使用C#OLEDB ACE引擎處理xls和xlsx文件格式。 在我的本地計算機和本地托管的IIS服務器中,它都能正常工作。 但是,當我上傳.ibfs文件格式時,出現了問題。

樣品輸入

在此處輸入圖片說明

在這里,我發布了我最有效的兩種方法:

方法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#的解決方案-在沒有Office組件的情況下將xls文件轉換為xlsx

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);
        }

如果IBFS文件是Excel文件,則可以嘗試使用Essential XlsIO 我找不到要檢查的IBFS文件。

如果您有資格,則可以通過社區許可計划免費獲得整套控件(也包括商業應用程序)。 社區許可證是完整的產品,沒有任何限制或水印。

注意:我為Syncfusion工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM