1、安装引用ExcelLibrary
通过NuGet获取ExcelLibrary和手动引用
1)使用Nuget管理控制台
将ExcelLibrary集成到项目中的最简单方法是使用NuGet。您可以通过打开包管理器控制台(PM)并键入以下语句来安装ExcelLibrary
:
Install-Package ExcelLibrary
2)使用Nuget图形管理器
使用Nuget的界面的管理器搜索"ExcelLibrary"
=> 找到点出点击"安装"
。
相关文档:VS(Visual Studio)中Nuget的使用
手动下载:https://code.google.com/archive/p/excellibrary/downloads
2、使用ExcelLibrary读取Excel示例代码
var workbook = Workbook.Load("spreadsheet.xls");
var worksheet = workbook.Worksheets[0]; // assuming only 1 worksheet
var cells = worksheet.Cells;
var dataTable = new DataTable("datatable");
// add columns
dataTable.Columns.Add("column1");
dataTable.Columns.Add("column2");
...
// add rows
for (int rowIndex = cells.FirstRowIndex + 1; rowIndex <= cells.LastRowIndex; rowIndex++)
{
var values = new List<string>();
foreach(var cell in cells.GetRow(rowIndex))
{
values.Add(cell.Value.StringValue);
}
dataTable.LoadDataRow(values.ToArray(), true);
}
或者
//create new xls file
string file = "C:\newdoc.xls";
Workbook workbook = new Workbook();
Worksheet worksheet = new Worksheet("First Sheet");
worksheet.Cells[0, 1] = new Cell((short)1);
worksheet.Cells[2, 0] = new Cell(9999999);
worksheet.Cells[3, 3] = new Cell((decimal)3.45);
worksheet.Cells[2, 2] = new Cell("Text string");
worksheet.Cells[2, 4] = new Cell("Second string");
worksheet.Cells[4, 0] = new Cell(32764.5, "#,##0.00");
worksheet.Cells[5, 1] = new Cell(DateTime.Now, @"YYYY-MM-DD"); worksheet.Cells.ColumnWidth[0, 1] = 3000;
workbook.Worksheets.Add(worksheet); workbook.Save(file);
// open xls file
Workbook book = Workbook.Load(file);
Worksheet sheet = book.Worksheets[0];
// traverse cells
foreach (Pair, Cell> cell in sheet.Cells)
{
dgvCells[cell.Left.Right, cell.Left.Left].Value = cell.Right.Value;
}
// traverse rows by Index
for (int rowIndex = sheet.Cells.FirstRowIndex; rowIndex <= sheet.Cells.LastRowIndex; rowIndex++)
{
Row row = sheet.Cells.GetRow(rowIndex);
for (int colIndex = row.FirstColIndex; colIndex <= row.LastColIndex; colIndex++)
{
Cell cell = row.GetCell(colIndex);
}
}
ExcelLibrary源码:https://storage.googleapis.com/google-code-archive-source/v2/code.google.com/excellibrary/source-archive.zip