1.添加DLL
using NPOI.XSSF.Streaming;
using NPOI.XSSF.UserModel;
using NPOI.SS.UserModel;
using System.Collections.Generic;
using System.Data;
using System.IO;
/// <summary>
///
/// </summary>
/// <param name="excelDatas">导出表格的数据</param>
/// <param name="dic">导出表格表头的名字 key:插入的</param>
/// <param name="exportPath">导出路径</param>
/// <param name="sheetName">表名</param>
public static void Export(DataTable excelDatas, Dictionary<string, string> dic, string exportPath, string sheetName = "Sheet1")
{
//添加列名
HashSet<string> hashSet = new HashSet<string>();
foreach (DataColumn column in excelDatas.Columns)
{
hashSet.Add(column.ColumnName);
}
IEnumerable<string> keys = dic.Keys.Intersect(hashSet);
Dictionary<string, string> dictionary = dic.Where((KeyValuePair<string, string> p) => keys.Contains(p.Key)).ToDictionary((KeyValuePair<string, string> p) => p.Key, (KeyValuePair<string, string> p) => p.Value);
//行数
int rowNum = 0;
//列数
int cloumNum = 0;
//工作簿
IWorkbook workBook = (IWorkbook)(object)new XSSFWorkbook();
//创建表
ISheet createSheet = workBook.CreateSheet(sheetName);
//创建行
IRow createRow = createSheet.CreateRow(rowNum);
foreach (KeyValuePair<string, string> item in dictionary)
{
//创建单元格
ICell createCell = createRow.CreateCell(cloumNum);
createCell.SetCellValue(item.Value);
cloumNum++;
}
rowNum++;
foreach (DataRow row in excelDatas.Rows)
{
createRow = createSheet.CreateRow(rowNum);
cloumNum = 0;
foreach (KeyValuePair<string, string> item in dictionary)
{
object obj = row[item.Key];
DataColumn dataColumn2 = excelDatas.Columns[item.Key];
ICell cell = createRow.CreateCell(cloumNum);
SetCellValue(cell, obj, dataColumn2.DataType);
cloumNum++;
}
rowNum++;
}
AdjustColumnWidth(createSheet, dictionary.Count);
Export(workBook, exportPath);
}
private static void Export(IWorkbook workbook, string exportPath)
{
try
{
FileStream fileStream = null;
FileInfo fileInfo = new FileInfo(exportPath);
string directoryName = fileInfo.DirectoryName;
if (!Directory.Exists(directoryName))
{
Directory.CreateDirectory(directoryName);
}
try
{
fileStream = new FileStream(exportPath, FileMode.Open, FileAccess.Write, FileShare.Write, bufferSize: 4096, useAsync: true);
workbook.Write(fileStream);
workbook.Close();
}
finally
{
if (fileStream != null)
{
fileStream.Close();
fileStream.Dispose();
}
}
}
catch (Exception ex)
{
LogHelper.Proxy.Error(ex);
}
finally
{
}
}
/// <summary>
/// 调整列的宽度
/// </summary>
/// <param name="sheet">表名</param>
/// <param name="maxColumn"></param>
private static void AdjustColumnWidth(ISheet sheet, int maxColumn)
{
for (int columnNum = 0; columnNum < maxColumn; columnNum++)
{
int columnWidth = sheet.GetColumnWidth(columnNum) / 256;
for (int rowNum = 0; rowNum < sheet.LastRowNum; rowNum++)
{
IRow currentRow = sheet.GetRow(rowNum) ?? sheet.CreateRow(rowNum);
//当前行未被使用过
if (currentRow.GetCell(columnNum) != null)
{
ICell currentCell = currentRow.GetCell(columnNum);
int length = Encoding.Default.GetBytes(currentCell.ToString()).Length;
if (columnWidth < length)
{
columnWidth = length + 2;
}
}
}
sheet.SetColumnWidth(columnNum, columnWidth * 256);
}
}
private static void SetCellValue(ICell cell, object obj, Type targetType = null)
{
if (obj == null)
{
cell.SetCellValue("");
return;
}
if (targetType == null)
{
targetType = obj.GetType();
}
if (targetType == typeof(byte) || targetType == typeof(byte?)
|| targetType == typeof(short) || targetType == typeof(short?)
|| targetType == typeof(int) || targetType == typeof(int?))
{
cell.SetCellValue(Convert.ToInt32(obj));
}
else if (targetType == typeof(float) || targetType == typeof(float?)
|| targetType == typeof(double) || targetType == typeof(double?))
{
cell.SetCellValue(double.Parse(obj.ToString()));
}
else if (targetType == typeof(IRichTextString))
{
cell.SetCellValue((IRichTextString)obj);
}
else if (targetType == typeof(string))
{
cell.SetCellValue(obj.ToString());
}
else if (targetType == typeof(DateTime) || targetType == typeof(DateTime?))
{
cell.SetCellValue(((DateTime)obj).ToString("yyyy-MM-dd HH:mm:ss"));
}
else if (targetType == typeof(bool) || targetType == typeof(bool?))
{
cell.SetCellValue(Convert.ToBoolean(obj));
}
else
{
cell.SetCellValue(obj.ToString());
}
}
}