通过NPOI将DataTable导出成Excel时,每列内容长度不一,统一设置宽度当然不太合理了,所以研究了下动态设置列宽。
首先根据表头内容长度计算列宽,并将每列的列宽存于Dictionary<int, int>中,分别为每列序号和每列宽度。
然后在循环每行信息对每列内容赋值时,计算内容对应列宽,如超过表头的宽度则替换Dictionary中的宽度值,注意Excel限制最大宽度为15000,超出则指定为15000。
注:内容自动换行后,行高会被撑开,项目导出格式需要,所以下面代码中固定了行高,可根据需求自行判断是否需要固定行高。
/// <summary>
/// Datable导出成Excel
/// </summary>
/// <param name="dt"></param>
/// <param name="file">导出路径(包括文件名与扩展名)</param>
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
{
return;
}
// 标题及内容单元格样式
var headCellStyle = CreateCellStyle(workbook, true);
var contentCellStyle = CreateCellStyle(workbook, false);
// 每列列宽字典
var dic = new Dictionary<int, int>();
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);
cell.CellStyle = headCellStyle;
dic.Add(i, Encoding.Default.GetBytes(cell.StringCellValue).Length * 256 + 200);
}
//数据
for (int i = 0; i < dt.Rows.Count; i++)
{
IRow row1 = sheet.CreateRow(i + 1);
// 行高,避免自动换行的内容将行高撑开
row1.HeightInPoints = 20f;
for (int j = 0; j < dt.Columns.Count; j++)
{
ICell cell = row1.CreateCell(j);
cell.SetCellValue(dt.Rows[i][j].ToString());
cell.CellStyle = contentCellStyle;
int length = Encoding.Default.GetBytes(cell.StringCellValue).Length * 256 + 200;
length = length > 15000 ? 15000 : length;
// 若比已存在列宽更宽则替换,Excel限制最大宽度为15000
if (dic[j] < length)
{
dic[j] = length;
}
}
}
for (int i = 0; i < dt.Columns.Count; i++)
{
sheet.SetColumnWidth(i, dic[i]);
}
//转为字节数组
MemoryStream stream = new MemoryStream();
workbook.Write(stream);
var buf = stream.ToArray();
//保存为Excel文件
using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write))
{
fs.Write(buf, 0, buf.Length);
fs.Flush();
}
}
/// <summary>
/// 单元格样式
/// </summary>
/// <param name="workbook"></param>
/// <param name="isHead"></param>
/// <returns></returns>
private static ICellStyle CreateCellStyle(IWorkbook workbook, bool isHead)
{
var cellStyle = workbook.CreateCellStyle();
var font = workbook.CreateFont();
font.IsBold = isHead; // 粗体
cellStyle.SetFont(font);
if (isHead)
{
cellStyle.Alignment = HorizontalAlignment.Center; // 水平居中
cellStyle.VerticalAlignment = VerticalAlignment.Center; // 垂直居中
}
cellStyle.BorderTop = BorderStyle.Thin;
cellStyle.BorderBottom = BorderStyle.Thin;
cellStyle.BorderLeft = BorderStyle.Thin;
cellStyle.BorderRight = BorderStyle.Thin;
cellStyle.WrapText = true;//内容自动换行,避免存在换行符的内容合并成单行
return cellStyle;
}