.Net C# 使用NPIOI创建Word文档
2021-06-14 01:06
标签:tostring click 文件 word 第一个 url current vat reac .Net C# 使用NPIOI创建Word文档 标签:tostring click 文件 word 第一个 url current vat reac 原文地址:https://www.cnblogs.com/Aaron-Lee/p/10436348.htmlusing System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
using NPOI;
using NPOI.OpenXmlFormats.Wordprocessing;
using NPOI.XWPF.UserModel;
namespace ExportToWord.Report
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Export_Click(object sender, EventArgs e)
{
XWPFDocument doc;
String template = AppDomain.CurrentDomain.BaseDirectory + "Template\\ReportTemplate.docx"; //模板地址
using (FileStream stream = new FileStream(template, FileMode.Open, FileAccess.Read))
{
doc = new XWPFDocument(stream);
for(int i=0;i)
{
for(int j=1;j4; j++) //给模板里的第一个table添加行和数据
{
if(j==1||j==2)
{
doc.Tables[0].Rows[j].GetCell(0).SetText("test");
}
else
{
doc.Tables[0].CreateRow();
doc.Tables[0].Rows[j].GetCell(0).SetText("1");
doc.Tables[0].Rows[j].CreateCell().SetText("2");
doc.Tables[0].Rows[j].CreateCell().SetText("3");
doc.Tables[0].Rows[j].CreateCell().SetText("4");
}
}
}
stream.Close();
}
String filename = "Report_" + DateTime.Now.ToString("yyyyMMddHHmm") + ".docx";
String fullpath = AppDomain.CurrentDomain.BaseDirectory + "Documents\\" + filename;
FileStream file = new FileStream(fullpath, FileMode.Create, FileAccess.Write);
doc.Write(file);
file.Close();
System.IO.FileInfo fileInfo = new System.IO.FileInfo(fullpath); //返回Word流文件
if (fileInfo.Exists == true)
{
const long ChunkSize = 102400;
byte[] buffer = new byte[ChunkSize];
Response.Clear();
System.IO.FileStream iStream = System.IO.File.OpenRead(fullpath);
long dataLengthToRead = iStream.Length;
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(filename));
while (dataLengthToRead > 0 && Response.IsClientConnected)
{
int lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(ChunkSize));
Response.OutputStream.Write(buffer, 0, lengthRead);
Response.Flush();
dataLengthToRead = dataLengthToRead - lengthRead;
}
Response.Close();
iStream.Close();
Response.End();
}
}
private static void ReplaceKey(XWPFParagraph para, string content) //拓展方法
{
string text = "";
foreach (var run in para.Runs)
{
text = run.ToString();
run.SetText(content, 0);
}
}
}
}
上一篇:Hibernate入门
下一篇:java 常量池
文章标题:.Net C# 使用NPIOI创建Word文档
文章链接:http://soscw.com/index.php/essay/93919.html