如何在不使用Microsoft.Office.Interop.Excel库的情况下在C#中读取excel文件

ASD*_*ASD 43 .net c# excel office-interop

我在C#中有一个.Net-Windows应用程序.我需要打开一个excel并处理它.如何在不使用Microsoft.Office.Interop.Excel库的情况下执行此操作?

Moh*_*han 57

我强烈建议使用CSharpJExcel读取Excel 97-2003文件(xls)和ExcelPackage以读取Excel 2007/2010文件(Office Open XML格式,xlsx).

它们都很完美.他们绝对不依赖任何东西.

使用CSharpJExcel的示例:

Workbook workbook = Workbook.getWorkbook(new System.IO.FileInfo(fileName));
var sheet = workbook.getSheet(0);
...
var content = sheet.getCell(colIndex, rowIndex).getContents();
...
workbook.close();
Run Code Online (Sandbox Code Playgroud)

使用ExcelPackage的示例:

using (ExcelPackage xlPackage = new ExcelPackage(existingFile))
{
  // get the first worksheet in the workbook
  ExcelWorksheet worksheet = xlPackage.Workbook.Worksheets[1];
  int iCol = 2;  // the column to read

  // output the data in column 2
  for (int iRow = 1; iRow < 6; iRow++)
    Console.WriteLine("Cell({0},{1}).Value={2}", iRow, iCol, 
      worksheet.Cell(iRow, iCol).Value);

  // output the formula in row 6
  Console.WriteLine("Cell({0},{1}).Formula={2}", 6, iCol, 
    worksheet.Cell(6, iCol).Formula);

} // the using statement calls Dispose() which closes the package.
Run Code Online (Sandbox Code Playgroud)

编辑:

还有另一个项目ExcelDataReader似乎能够处理这两种格式.它也像我提到的其他一样容易.

还有其他图书馆:

  • 这个ExcelDataReader比OLEDB更加令人敬畏和快得多. (3认同)
  • ExcelDataReader 正在迁移到 GitHub:https://github.com/ExcelDataReader/ExcelDataReader (2认同)

Ale*_*tic 40

var fileName = @"C:\ExcelFile.xlsx";
var connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;IMEX=1;HDR=NO;TypeGuessRows=0;ImportMixedTypes=Text\""; ;
using (var conn = new OleDbConnection(connectionString))
{
    conn.Open();

    var sheets = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
    using (var cmd = conn.CreateCommand())
    {
        cmd.CommandText = "SELECT * FROM [" + sheets.Rows[0]["TABLE_NAME"].ToString() + "] ";

        var adapter = new OleDbDataAdapter(cmd);
        var ds = new DataSet();
        adapter.Fill(ds);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 注意 - 当工作表受密码保护时,OLEDB不起作用. (3认同)