因为工作需要,设计一个导出word表格的功能。
首先导入Aspose.word(网上百度随便下的)
首先建立一个word 模板
然后在下一行的起始位置插入一个书签
下面直接上代码
string tempFile = HostingEnvironment.MapPath("~/Template/上图设置的模板名称.doc");//获取模板路径
Document doc = new Document(tempFile);
DocumentBuilder builder = new DocumentBuilder(doc);
DataTable products = this.IOC_IZTCXService.ExportNJFAJJNML(Request.Params, this.LoginedUser.UserID); //数据源 (调用的外部方法)
List<double> widthList = new List<double>();
for (var i = 0; i < products.Columns.Count; i++)
{
builder.MoveToCell(0, 0, i, 0); //移动单元格
double width = builder.CellFormat.Width;//获取单元格宽度
widthList.Add(width);
}
builder.MoveToBookmark("table"); //开始添加值
for (var m = 0; m < products.Rows.Count; m++)
{
for (var i = 0; i < products.Columns.Count; i++)
{
builder.InsertCell(); // 添加一个单元格
builder.CellFormat.Borders.LineStyle = LineStyle.Single;
builder.CellFormat.Borders.Color = System.Drawing.Color.Black;
builder.CellFormat.Width = widthList[i];
builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
builder.Write(products.Rows[m][i].ToString());
}
builder.EndRow();
}
doc.Range.Bookmarks["table"].Text = ""; // 清掉书签标识
MemoryStream outStream = new MemoryStream();
doc.Save(outStream, SaveFormat.Doc);
Response.Clear();
Response.Buffer = true;
Response.Charset = "utf-8";
Response.AppendHeader("Content-Disposition", "attachment;filename=" +
System.Web.HttpUtility.UrlEncode("导出文件的名称.doc", System.Text.Encoding.UTF8).ToString());
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.ContentType = "application/ms-excel";
Response.BinaryWrite(outStream.ToArray());
Response.End();