一、读取Excel
public static void ReadExcel()
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Excel|*.xlsx;*.xls";
if (ofd.ShowDialog() == DialogResult.OK)
{
IWorkbook workbook = null;
using (FileStream file = new FileStream(ofd.FileName, FileMode.Open, FileAccess.Read))
{
workbook = WorkbookFactory.Create(ofd.FileName);
}
ISheet sheet0 = workbook.GetSheetAt(0);
System.Collections.IEnumerator rows = sheet0.GetRowEnumerator();
var cellCount = sheet0.GetRow(0).LastCellNum;
for (int i = sheet0.FirstRowNum ; i <= sheet0.LastRowNum; i++)
{
IRow row = sheet0.GetRow(i);
var cell0 = row.GetCell(0).ToString();
var cell1 = row.GetCell(1).ToString();
}
}
}
二、导出到Excel
public static void TableToExcel(DataTable dt, string file)
{
IWorkbook workbook;
string fileExt = Path.GetExtension(file).ToLower();
if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(); } else if (fileExt == ".xls") { workbook = new HSSFWorkbook(); } else { workbook = null; }
if (workbook == null) { return; }
ISheet sheet = string.IsNullOrEmpty(dt.TableName) ? workbook.CreateSheet("Sheet1") : workbook.CreateSheet(dt.TableName);
IRow row = sheet.CreateRow(0);
for (int i = 0; i < dt.Columns.Count; i++)
{
ICell cell = row.CreateCell(i);
cell.SetCellValue(dt.Columns[i].ColumnName);
}
for (int i = 0; i < dt.Rows.Count; i++)
{
IRow row1 = sheet.CreateRow(i + 1);
for (int j = 0; j < dt.Columns.Count; j++)
{
ICell cell = row1.CreateCell(j);
cell.SetCellValue(dt.Rows[i][j].ToString());
}
}
MemoryStream stream = new MemoryStream();
workbook.Write(stream);
var buf = stream.ToArray();
using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write))
{
fs.Write(buf, 0, buf.Length);
fs.Flush();
}
}