直接上代碼吧,工具類,爲了以後要使用可以直接拷貝過去使用方便~
public class ExcelService
{
public static DataTable ReadExcelToDataTable(string filePath, string sheetName)
{
var data = new DataTable();
if (string.IsNullOrWhiteSpace(filePath)) throw new Exception("要讀取的文件路徑不能爲空!");
//讀取文件
IWorkbook workbook = null;
using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
string a = ".xlsx";
string b = ".xls";
string exName = Path.GetExtension(filePath);
if (exName.IndexOf(a) > 0) workbook = new XSSFWorkbook(fs);
if (exName.IndexOf(b) > 0) workbook = new HSSFWorkbook(fs);
}
if (workbook == null) throw new Exception("文件不合法!");
//讀取Sheet
ISheet sheet = null;
if (!string.IsNullOrWhiteSpace(sheetName)) sheet = workbook.GetSheet(sheetName);
if (sheet == null) sheet = workbook.GetSheetAt(0);
if (sheet == null) throw new Exception("未讀取到任何Sheet信息!");
IRow firstRow = sheet.GetRow(0);//讀取第一行
int cellCount = firstRow.LastCellNum;//拿到第一行的列的數量
//第一行是列信息,初始化表格列
for (int i = firstRow.FirstCellNum; i < cellCount; i++)
{
ICell cell = firstRow.GetCell(i);
if (cell == null) throw new Exception(string.Format("未讀取到第{0}列列名!", i));
string cellValue = cell.StringCellValue;
if (!string.IsNullOrWhiteSpace(cellValue))
{
DataColumn column = new DataColumn(cellValue);
data.Columns.Add(column);
}
}
int startRow = sheet.FirstRowNum + 1;//行開始索引
int rowCount = sheet.LastRowNum + 1;//總行數,因爲第一行是列信息,所以需要+1
for (int i = startRow; i < rowCount; i++)
{
IRow row = sheet.GetRow(i);
if (row == null) continue;
DataRow dataRow = data.NewRow();
for (int j = row.FirstCellNum; j < cellCount; ++j)
{
var cell = row.GetCell(j);
if (cell != null) dataRow[j] = cell.ToString();
}
data.Rows.Add(dataRow);
}
return data;
}
public static void Export(string filePath, params Tuple<string, DataTable>[] dataList)
{
if (string.IsNullOrWhiteSpace(filePath)) throw new Exception("導出路徑不能爲空!");
if (dataList == null || dataList.Length <= 0) throw new Exception("沒有需要導出的數據!");
var workbook = new XSSFWorkbook();
int index = 0;
foreach (var dataItem in dataList)
{
string sheetName = dataItem.Item1;
var data = dataItem.Item2;
index++;
if (string.IsNullOrWhiteSpace(sheetName)) sheetName = "Sheet" + index;
var sheet = workbook.CreateSheet(sheetName);
IRow row;
ICell cell;
int startRowIndex = 0;
//列頭
row = sheet.CreateRow(startRowIndex++);
for (int i = 0; i < data.Columns.Count; i++)
{
cell = row.CreateCell(i);
string columnName = data.Columns[i].ColumnName;
cell.SetCellValue(columnName);
}
//數據
for (int i = 0; i < data.Rows.Count; i++)
{
int rowIndexItem = i + startRowIndex;
row = sheet.CreateRow(rowIndexItem);
var rowData = data.Rows[i];
for (int j = 0; j < data.Columns.Count; j++)
{
cell = row.CreateCell(j);
string columnValue = rowData[j].ToString();
cell.SetCellValue(columnValue);
}
}
//自動列寬
for (int i = 0; i < data.Rows.Count + 1; i++)
{
sheet.AutoSizeColumn(i);
}
}
using (FileStream fs = new FileStream(filePath, FileMode.Create))
{
workbook.Write(fs);
}
}
}
Ending~