我强烈推荐使用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();
使用 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.
编辑:
有另一个项目ExcelDataReader,似乎能够处理这两种文件格式。它与我提到的其他库一样简单易用。
还有其他的库:
NPOI:Apache POI库的.NET端口:
非常强大、免费且开源。除了Excel(97-2010)外,它还支持Word和PowerPoint文件。
ExcelLibrary:
仅支持Excel 97-2003(xls)文件。
EPPlus:
ExcelPackage的扩展。使用起来更容易(我猜的)。
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);
}
}
public void ReadExcelCellTest()
{
XDocument document = XDocument.Load(@"C:\BDATA\Cars.xml");
XNamespace workbookNameSpace = @"urn:schemas-microsoft-com:office:spreadsheet";
// Get worksheet
var query = from w in document.Elements(workbookNameSpace + "Workbook").Elements(workbookNameSpace + "Worksheet")
where w.Attribute(workbookNameSpace + "Name").Value.Equals("Settings")
select w;
List<XElement> foundWoksheets = query.ToList<XElement>();
if (foundWoksheets.Count() <= 0) { throw new ApplicationException("Worksheet Settings could not be found"); }
XElement worksheet = query.ToList<XElement>()[0];
// Get the row for "Seat"
query = from d in worksheet.Elements(workbookNameSpace + "Table").Elements(workbookNameSpace + "Row").Elements(workbookNameSpace + "Cell").Elements(workbookNameSpace + "Data")
where d.Value.Equals("Seat")
select d;
List<XElement> foundData = query.ToList<XElement>();
if (foundData.Count() <= 0) { throw new ApplicationException("Row 'Seat' could not be found"); }
XElement row = query.ToList<XElement>()[0].Parent.Parent;
// Get value cell of Etl_SPIImportLocation_ImportPath setting
XElement cell = row.Elements().ToList<XElement>()[1];
// Get the value "Leon"
string cellValue = cell.Elements(workbookNameSpace + "Data").ToList<XElement>()[0].Value;
Console.WriteLine(cellValue);
}
我最近发现了这个库,它可以将Excel工作簿文件转换成DataSet: Excel Data Reader
(说明:该库可以帮助将Excel文件转换为DataSet格式,方便IT技术人员处理数据)寻找GSpread.NET。 它也是一个开源项目,不需要安装Office。 您可以使用Microsoft Excel的API来使用Google电子表格。 如果您想重复使用旧代码以访问Google电子表格,则GSpread.NET是最好的方法。 您需要添加几行:
Set objExcel = CreateObject("GSpreadCOM.Application")
// Name - User name, any you like
// ClientIdAndSecret - `client_id|client_secret` format
// ScriptId - Google Apps script ID
app.MailLogon(Name, ClientIdAndSecret, ScriptId);
DataSet ds_Data = new DataSet();
OleDbConnection oleCon = new OleDbConnection();
string strExcelFile = @"C:\Test.xlsx";
oleCon.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strExcelFile + ";Extended Properties=\"Excel 12.0;IMEX=1;HDR=NO;TypeGuessRows=0;ImportMixedTypes=Text\"";;
string SpreadSheetName = "";
OleDbDataAdapter Adapter = new OleDbDataAdapter();
OleDbConnection conn = new OleDbConnection(sConnectionString);
string strQuery;
conn.Open();
int workSheetNumber = 0;
DataTable ExcelSheets = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
SpreadSheetName = ExcelSheets.Rows[workSheetNumber]["TABLE_NAME"].ToString();
strQuery = "select * from [" + SpreadSheetName + "] ";
OleDbCommand cmd = new OleDbCommand(strQuery, conn);
Adapter.SelectCommand = cmd;
DataSet dsExcel = new DataSet();
Adapter.Fill(dsExcel);
conn.Close();
你也可以像我一样购买商业控件,比如这个: http://www.syncfusion.com/products/reporting-edition/xlsio
我曾经苦苦挣扎多年,最终选择了商业解决方案。我首先尝试了OLEDB方法,在我的开发环境中非常容易使用,但是部署起来可能会很麻烦。然后我尝试了开源解决方案,但大多数都已经过时且支持不佳。
Syncfusion的xlsio控件正是我使用并感到满意的控件,但还有其他选择。如果你能负担得起,不要犹豫,这是最好的解决方案。为什么?因为它没有与系统的依赖关系,并立即支持所有版本的Office。除此之外,它还非常快速。
不,我不是Syncfusion的员工 ;)