NPOI导出Word并插入表格和图片

一、NPOI导出Word

NPOI导出Word并插入图片,会遇到打开显示不出来的图片的情况,下面写的例子,在本地或服务器上导出都显示正常(亲测有效)。

二、引用

引用文件NPOI.dll、NPOI.OOXML.dll、NPOI.OpenXml4Net.dll、NPOI.OpenXmlFormats.dll

using NPOI.HPSF;
using NPOI.HSSF.Util;
using NPOI.XWPF.UserModel;

三、创建文档、插入表格和图片

XWPFDocument doc = new XWPFDocument();
XWPFTable table = doc.CreateTable(dt.Rows.Count + 1, dt.Columns.Count);
//增加表头信息
for (int i = 0; i < dt.Columns.Count; i++)
{
	var title = table.GetRow(0).GetCell(i);
	XWPFParagraph par = title.AddParagraph();
	XWPFRun run = par.CreateRun();
	par.Alignment =ParagraphAlignment.CENTER;//水平居中显示
	run.FontFamily = "宋体";
	run.FontSize = 18;
    run.SetText(dt.Columns[i].ColumnName);
}
//增加内容信息
for (int i = 0; i < dt.Rows.Count; i++)
{
	for (int j = 0; j < dt.Columns.Count; j++)
	{
		var Cell = table.GetRow(i + 1).GetCell(j);
		XWPFParagraph par = Cell.AddParagraph();
		XWPFRun run = par.CreateRun();
		par.Alignment =ParagraphAlignment.CENTER;//水平居中显示
		Cell.SetVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);//垂直居中
		string Vt = Convert.ToString(dt.Rows[i][j]);
		if (j < dt.Columns.Count - 1)
        {
           run.FontFamily = "宋体";
           run.FontSize = 16;
           run.SetText(Vt);
       }
       else
       {
          //插入图片 
          using (FileStream fsImg = new FileStream(dt.Rows[i][j].ToString(), FileMode.OpenOrCreate, FileAccess.Read))
          {
              run.AddPicture(fsImg, (int)PictureType.PNG, i + "_" + j + ".png", (int)(200.0 * 9525), (int)(200.0 * 9525));  //长和宽必须乘上9525
          }
       }
	}
}
using (MemoryStream ms = new MemoryStream())
{
	doc.Write(ms);
	var buf = ms.ToArray();
	//流方式下载文件
    HttpContext.Current.Response.ContentType = "application/octet-stream";
    //通知浏览器下载文件而不是打开
    HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode("xxx.doc", System.Text.Encoding.UTF8));
    HttpContext.Current.Response.BinaryWrite(buf);
    HttpContext.Current.Response.Flush();
    HttpContext.Current.Response.End();
    ms.Flush();
    ms.Position = 0;
}

你可能感兴趣的:(日常笔记,c#,.net)