using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
namespace Team.Utility
{
///
/// poi类库实现的excel工具类
/// excel文件到table,table到excel
///
public static class ExcelUtil
{
///
/// Excel导入成Datable
///
/// 导入路径(包含文件名与扩展名)
///
///
///
/// Exception("无效的文件扩展名"),要求xls,xlsx格式
public static DataTable ExcelToTable(string file,bool isFirstRowAsHeader=true)
{
var dt = new DataTable();
var fileExt = Path.GetExtension(file)?.ToLower();
using var fs = new FileStream(file, FileMode.Open, FileAccess.Read,FileShare.ReadWrite);
//XSSFWorkbook 适用XLSX格式,HSSFWorkbook 适用XLS格式
IWorkbook workbook = fileExt switch
{
".xlsx" => new XSSFWorkbook(fs),
".xls" => new HSSFWorkbook(fs),
_ => throw new Exception("无效的文件扩展名")
};
var sheet = workbook.GetSheetAt(0);
var columns = new List();
//表头
var header = sheet.GetRow(sheet.FirstRowNum);
for (var i = 0; i < header.LastCellNum; i++)
{
var obj = GetValueType(header.GetCell(i));
if (obj == null || obj.ToString() == string.Empty||!isFirstRowAsHeader)
dt.Columns.Add(new DataColumn("Columns" + i));
else
dt.Columns.Add(new DataColumn(obj.ToString()));
columns.Add(i);
}
var firstRow = isFirstRowAsHeader ? sheet.FirstRowNum + 1 : sheet.FirstRowNum;
//数据
for (var i = firstRow; i <= sheet.LastRowNum; i++)
{
var dr = dt.NewRow();
var hasValue = false;
foreach (var j in columns)
{
dr[j] = GetValueType(sheet.GetRow(i).GetCell(j));
if (dr[j] != null && dr[j].ToString() != string.Empty)
{
hasValue = true;
}
}
if (hasValue)
{
dt.Rows.Add(dr);
}
}
return dt;
}
///
/// Datable导出成Excel
///
///
/// 导出路径(包括文件名与扩展名)
/// 默认添加表头
/// Exception("无效的文件扩展名"),要求xls,xlsx格式
public static void TableToExcel(DataTable dt, string file,bool isAddHeader=true)
{
var fileExt = Path.GetExtension(file)?.ToLower();
IWorkbook workbook = fileExt switch
{
".xlsx" => new XSSFWorkbook(),
".xls" => new HSSFWorkbook(),
_ => throw new Exception("无效的文件扩展名")
};
var sheet = string.IsNullOrEmpty(dt.TableName) ? workbook.CreateSheet("Sheet1") : workbook.CreateSheet(dt.TableName);//sheet名
if (isAddHeader)
{
var row = sheet.CreateRow(0);
for (var i = 0; i < dt.Columns.Count; i++)
{
var cell = row.CreateCell(i);
cell.SetCellValue(dt.Columns[i].ColumnName);
}
//数据
}
for (var i = 0; i < dt.Rows.Count; i++)
{
var row1 = sheet.CreateRow(i + 1);
for (var j = 0; j < dt.Columns.Count; j++)
{
var cell = row1.CreateCell(j);
cell.SetCellValue(dt.Rows[i][j].ToString());
}
}
//表头
//转为字节数组
using var stream = new MemoryStream();
workbook.Write(stream);
var buf = stream.ToArray();
//保存为Excel文件
using var fs = new FileStream(file, FileMode.Create, FileAccess.Write);
fs.Write(buf, 0, buf.Length);
fs.Flush();
}
public static IRow ExtensionMethod(ISheet sheet,int rowIndex)
{
var row= sheet.CreateRow(rowIndex);
return row;
}
public static void TableToExcel(DataTable []dts, string file)
{
IWorkbook workbook;
var 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; }
foreach (var dt in dts)
{
var sheet = string.IsNullOrEmpty(dt.TableName) ? workbook.CreateSheet($"Sheet{dts.ToList().IndexOf(dt)}") : workbook.CreateSheet(dt.TableName);
//表头
var row = sheet.CreateRow(0);
for (var i = 0; i < dt.Columns.Count; i++)
{
var cell = row.CreateCell(i);
cell.SetCellValue(dt.Columns[i].ColumnName);
}
//数据
for (var i = 0; i < dt.Rows.Count; i++)
{
var row1 = sheet.CreateRow(i + 1);
for (var j = 0; j < dt.Columns.Count; j++)
{
var cell = row1.CreateCell(j);
cell.SetCellValue(dt.Rows[i][j].ToString());
}
}
}
//转为字节数组
var stream = new MemoryStream();
workbook.Write(stream);
var buf = stream.ToArray();
//保存为Excel文件
using (var fs = new FileStream(file, FileMode.Create, FileAccess.Write))
{
fs.Write(buf, 0, buf.Length);
fs.Flush();
}
}
///
/// 获取单元格类型
///
///
///
private static object GetValueType(ICell cell)
{
if (cell == null)
return null;
switch (cell.CellType)
{
case CellType.Blank: //BLANK:
return null;
case CellType.Boolean: //BOOLEAN:
return cell.BooleanCellValue;
case CellType.Numeric: //NUMERIC:
return cell.NumericCellValue;
case CellType.String: //STRING:
return cell.StringCellValue;
case CellType.Error: //ERROR:
return cell.ErrorCellValue;
default:
return "=" + cell.CellFormula;
}
}
}
}