1. 使用GuGet引入NPOI包
搜素NPOI,然后点击右边的安装即可,因为我这边安装过了,所以出现了卸载与更新,因为有了新的稳定版本所以出现了更新。
2.导出DataTable到Word
/// <summary>
/// 导出文件到Word
/// </summary>
/// <param name="dataTable">数据集</param>
/// <param name="cPath">目录</param>
/// <param name="fileName">文件名称</param>
/// <param name="isSetCName">是否对表头进行重命名</param>
/// <returns></returns>
public string DataTable2Word(DataTable dataTable, string cPath, string fileName, bool isSetCName = true)
{
XWPFDocument doc = new XWPFDocument();
CT_SectPr srcpr = new CT_SectPr();
//设置A4纸纵向,如果要横向,两个值调换即可
srcpr.pgSz.w = (ulong)11906;
srcpr.pgSz.h = (ulong)16838;
srcpr.pgMar.left = (ulong)200;//左边距
srcpr.pgMar.right = (ulong)200;//右边距
srcpr.pgMar.top = "200";//上边距
srcpr.pgMar.bottom = "200";//下边距
doc.Document.body.sectPr = srcpr;
//输出标题
XWPFParagraph ptitle = doc.CreateParagraph();
ptitle.Alignment = ParagraphAlignment.CENTER;
XWPFRun titlerun = ptitle.CreateRun();
titlerun.SetText(fileName);
titlerun.IsBold = true;
titlerun.FontFamily = "微软雅黑";
titlerun.FontSize = 30;
titlerun.SetColor("black");
//声明整个表的大小 +1是为了增加一行表头
XWPFTable table = doc.CreateTable(dataTable.Rows.Count + 1, dataTable.Columns.Count);
//增加表头信息
for (int i = 0; i < dataTable.Columns.Count; i++)
{
if (isSetCName)
{
table.GetRow(0).GetCell(i).SetText(export.SetColumnName(dataTable.Columns[i].ColumnName,1));
}
else
{
table.GetRow(0).GetCell(i).SetText(dataTable.Columns[i].ColumnName);
}
}
//增加内容信息
for (int i = 0; i < dataTable.Rows.Count; i++)
{
for (int j = 0; j < dataTable.Columns.Count; j++)
{
string viewText = Convert.ToString(dataTable.Rows[i][j]);
table.GetRow(i + 1).GetCell(j).SetText(viewText);
}
}
//工作流写入,通过流的方式进行创建生成文件
MemoryStream stream = new MemoryStream();
doc.Write(stream);
byte[] buffer = stream.ToArray();
string filePath = System.Web.HttpContext.Current.Server.MapPath(cPath);
if (!Directory.Exists(filePath))//如果不存在就创建file文件夹
Directory.CreateDirectory(filePath);//创建该文件夹
fileName = fileName + ".docx";
string fullName = Path.Combine(filePath, fileName);
if (System.IO.File.Exists(fullName))
System.IO.File.Delete(fullName);
using (FileStream fs = new FileStream(fullName, FileMode.Create, FileAccess.Write))
{
try
{
fs.Write(buffer, 0, buffer.Length);
fs.Flush();
}
catch (Exception ex)
{
//异常不做任何处理,好处是让客户感觉没有问题,缺点是不利于查找程序的问题,需要日志文件跟踪。
Log.Instance.Error("DataTable2Word:" + ex.Message);
return "";
}
finally
{
fs.Dispose();//出现异常时,手动释放fs写对象
stream.Dispose();//出现异常时,手动释放stream流对象,防止卡死的现象
}
}
return fileName;
}
这里是我自己做的表头转换,就是利用DataTable的表头名称然后转换成想要转换成客户想看到的表头名称。