public static string DataTableToExcel(DataTable dt)
{
//bool result = false;
IWorkbook workbook = null;
FileStream fs = null;
IRow row = null;
IRow row1 = null;
ISheet sheet = null;
ISheet sheet1 = null;
ICell cell = null;
ICell cell1 = null;
try
{
if (dt != null && dt.Rows.Count > 0)
{
workbook = new XSSFWorkbook();
sheet = workbook.CreateSheet("Sheet1");//创建一个名称为Sheet0的表
sheet1 = workbook.CreateSheet("汇总");//创建一个名称为Sheet0的表
XSSFCellStyle cellStyle = (XSSFCellStyle)workbook.CreateCellStyle(); //创建列头样式
cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; //水平居中
cellStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
int rowCount = dt.Rows.Count;//行数
int columnCount = dt.Columns.Count;//列数
string data = DateTime.Now.ToString("yyyyMMddHHmmss");
//设置列头
row = sheet.CreateRow(0);//excel第一行设为列头
row1 = sheet1.CreateRow(0);//excel第一行设为列头
//int da = dt.Columns[1].MaxLength;
//sheet.DefaultColumnWidth = 20;
//sheet.SetColumnWidth(0,20*256);
//sheet.SetColumnWidth(1, 15 * 256);
//sheet.SetColumnWidth(2, 30 * 256);
for (int c = 0; c < columnCount; c++)
{
//cell = row.CreateCell(c);
cell = row.CreateCell(c);
cell.CellStyle = cellStyle;
sheet.AutoSizeColumn(c);
//cell.SetCellValue(dt.Columns[c].ColumnName);