using Microsoft.Office.Interop.Word; using NPOI.OpenXmlFormats.Wordprocessing; using NPOI.Util; using NPOI.XWPF.UserModel; using System; using System.Collections.Generic; using System.Data; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Reflection; using System.Web; using System.Web.Mvc; namespace WebApplication10.Controllers { public class HomeController : Controller { // GET: Home public ActionResult Index() { return View(); } public void test() { WordManage word = new WordManage(); MemoryStream ms = word.Export(); //MemoryStream ms = word.CreateWord(); Response.Clear(); Response.ClearHeaders(); //Response.Buffer = false; Response.ContentType = "application/octet-stream"; Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("output.docx", System.Text.Encoding.UTF8)); Response.BinaryWrite(ms.ToArray()); //Response.Flush(); ms.Close(); ms.Dispose(); } } public class WordManage { #region NPOI /// <summary> /// https://www.cnblogs.com/guohu/p/5573655.html /// </summary> /// <returns></returns> public MemoryStream CreateWord() { XWPFDocument doc = new XWPFDocument(); //创建新的word文档 // 插入文字 XWPFParagraph p1 = doc.CreateParagraph(); //向新文档中添加段落 p1.Alignment = ParagraphAlignment.CENTER; XWPFRun r1 = p1.CreateRun(); //向该段落中添加文字 r1.SetText("测试段落一"); r1.FontSize = 22; XWPFParagraph p2 = doc.CreateParagraph(); p2.Alignment = ParagraphAlignment.LEFT; XWPFRun r2 = p2.CreateRun(); r2.SetText("测试段落二"); // 插入图片 XWPFParagraph p3 = doc.CreateParagraph(); p3.Alignment = ParagraphAlignment.CENTER; XWPFRun r3 = p3.CreateRun(); Bitmap b = new Bitmap(@"E:\test project\WebApplication10\WebApplication10\Content\timg.jpg"); FileStream gfs = new FileStream(@"E:\test project\WebApplication10\WebApplication10\Content\timg.jpg", FileMode.Open, FileAccess.Read); r3.AddPicture(gfs, (int)PictureType.JPEG, "1.jpg", (b.Width / 5) * 10000, (b.Height / 5) * 10000); b.Dispose(); gfs.Close(); XWPFParagraph p4 = doc.CreateParagraph(); p2.Alignment = ParagraphAlignment.LEFT; XWPFRun r4 = p4.CreateRun(); r4.SetText("测试段落3"); // 表格 XWPFTable table = doc.CreateTable(5, 5); //XWPFTable table = new XWPFTable(m_CTTbl, m_Docx) table.Width = 1000 * 5; //table.SetColumnWidth(0, 1000);/* 设置列宽 */ //table.SetColumnWidth(1, 1500); //table.SetColumnWidth(2, 1500); //table.SetColumnWidth(3, 1000); //table.SetColumnWidth(4, 1000); table.GetRow(0).GetCell(0).SetParagraph(SetCellText( table, "地点")); table.GetRow(0).GetCell(1).SetParagraph(SetCellText( table, "日期")); table.GetRow(0).GetCell(2).SetParagraph(SetCellText( table, "男性")); table.GetRow(0).GetCell(3).SetParagraph(SetCellText( table, "女性")); table.GetRow(0).GetCell(4).SetParagraph(SetCellText( table, "合计")); System.IO.MemoryStream ms = new System.IO.MemoryStream(); doc.Write(ms); return ms; } public XWPFParagraph SetCellText( XWPFTable table, string setText) { //table中的文字格式设置 CT_P para = new CT_P(); XWPFParagraph pCell = new XWPFParagraph(para, table.Body); pCell.Alignment = ParagraphAlignment.CENTER;//字体居中 pCell.VerticalAlignment = TextAlignment.CENTER;//字体居中 XWPFRun r1c1 = pCell.CreateRun(); r1c1.SetText(setText); r1c1.FontSize = 12; r1c1.FontFamily = "华文楷体"; //r1c1.SetTextPosition(20);//设置高度 return pCell; } public MemoryStream Export() { string filepath = HttpContext.Current.Server.MapPath("~/Content/text.docx"); var tt = new { text = "cjc" }; var aa = new { pic = @"E:\test project\WebApplication10\WebApplication10\Content\timg.jpg" }; var ta = new { table = "cjc" }; using (FileStream stream = File.OpenRead(filepath)) { XWPFDocument doc = new XWPFDocument(stream); //遍历段落 foreach (var para in doc.Paragraphs) { ReplaceText(para, tt); ReplacePictures(para, aa); } ReplaceTable(doc); System.IO.MemoryStream ms = new System.IO.MemoryStream(); doc.Write(ms); return ms; } } private void ReplaceText(XWPFParagraph para, object model) { string text = para.ParagraphText; var runs = para.Runs; string styleid = para.Style; for (int i = 0; i < runs.Count; i++) { var run = runs[i]; text = run.ToString(); Type t = model.GetType(); PropertyInfo[] pi = t.GetProperties(); foreach (PropertyInfo p in pi) { //$$与模板中$$对应,也可以改成其它符号,比如{$name},务必做到唯一 if (text.Contains("$" + p.Name + "$")) { text = text.Replace("$" + p.Name + "$", p.GetValue(model, null).ToString()); } } run.SetText(text, 0); } } /// <summary> /// 插入图片 /// </summary> private void ReplacePictures(XWPFParagraph para, object model) { string text = para.ParagraphText; var runs = para.Runs; for (int i = 0; i < runs.Count; i++) { var run = runs[i]; text = run.ToString(); string path = string.Empty; Type t = model.GetType(); PropertyInfo[] pi = t.GetProperties(); foreach (PropertyInfo p in pi) { //$$与模板中$$对应,也可以改成其它符号,比如{$name},务必做到唯一 if (text.Contains("$" + p.Name + "$")) { path = p.GetValue(model, null).ToString(); text = text.Replace("$" + p.Name + "$", ""); break; } } run.SetText(text, 0); ReplacePicture(run, path); } } private void ReplacePicture(XWPFRun run, string path) { if (string.IsNullOrEmpty(path)) { return; } Bitmap b = new Bitmap(path); FileStream gfs = new FileStream(path, FileMode.Open, FileAccess.Read); int width = b.Width; int height = b.Height; double fold = 1; if (width > 600) { fold = width / 600.0; } width = Convert.ToInt32(width / fold); height = Convert.ToInt32(height / fold); run.AddPicture(gfs, (int)PictureType.JPEG, "1.jpg", Units.PixelToEMU(width), Units.PixelToEMU(height)); b.Dispose(); gfs.Close(); } private void ReplaceTables(XWPFDocument doc,XWPFParagraph para, object model) { string text = para.ParagraphText; var runs = para.Runs; string styleid = para.Style; for (int i = 0; i < runs.Count; i++) { var run = runs[i]; text = run.ToString(); Type t = model.GetType(); PropertyInfo[] pi = t.GetProperties(); foreach (PropertyInfo p in pi) { //$$与模板中$$对应,也可以改成其它符号,比如{$name},务必做到唯一 if (text.Contains("$" + p.Name + "$")) { ReplaceTable(doc); text = text.Replace("$" + p.Name + "$", ""); break; } } run.SetText(text, 0); } } private void ReplaceTable(XWPFDocument doc) { XWPFTable table = doc.Tables[0]; XWPFTableRow row = table.Rows[1]; CT_Row ctrow = row.GetCTRow(); table.RemoveRow(table.Rows.IndexOf(row)); //先移除模板行 for (int j = 0; j < 3; j++) { CT_Row targetRow = new CT_Row(); //复制cell结构 foreach (CT_Tc item in ctrow.Items) { CT_Tc addTc = targetRow.AddNewTc(); addTc.tcPr = item.tcPr;//cell样式,只包括列宽和cell对齐方式 IList<CT_P> list_p = item.GetPList(); foreach (var p in list_p) { CT_P addP = addTc.AddNewP(); addP.pPr = p.pPr;//段落样式 IList<CT_R> list_r = p.GetRList(); foreach (CT_R r in list_r) { CT_R addR = addP.AddNewR(); addR.rPr = r.rPr;//run样式 包括字体等 List<CT_Text> list_text = r.GetTList(); foreach (CT_Text text in list_text) { CT_Text addText = addR.AddNewT(); addText.space = text.space; addText.Value = text.Value; } } } } XWPFTableRow mrow = new XWPFTableRow(targetRow, table); table.AddRow(mrow); } } #endregion #region // Microsoft.Office.Interop.Word public void CreateWord2() { Application winword = new Application(); winword.Visible = false; object missing = Missing.Value; Microsoft.Office.Interop.Word.Document document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing); //页边距 document.PageSetup.LeftMargin = 40; //1.41CM document.PageSetup.RightMargin = 40; document.PageSetup.TopMargin = 40; document.PageSetup.BottomMargin = 40; //页眉 foreach (Microsoft.Office.Interop.Word.Section section in document.Sections) { //Get the header range and add the header details. Microsoft.Office.Interop.Word.Range headerRange = section.Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range; headerRange.Fields.Add(headerRange, Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage); headerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; headerRange.Font.ColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdBlue; headerRange.Font.Size = 10; headerRange.Text = "Header text goes here"; } //页脚 foreach (Microsoft.Office.Interop.Word.Section wordSection in document.Sections) { Microsoft.Office.Interop.Word.Range footerRange = wordSection.Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range; footerRange.Font.ColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdDarkRed; footerRange.Font.Size = 10; footerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; footerRange.Text = "Footer text goes here"; } //添加内容 document.Content.SetRange(0, 0); document.Content.Text = "检测报告 " + Environment.NewLine; //添加段落 Microsoft.Office.Interop.Word.Paragraph para1 = document.Content.Paragraphs.Add(ref missing); para1.Range.Text = "Para 1 text"; para1.Range.InsertParagraphAfter(); Microsoft.Office.Interop.Word.Paragraph para2 = document.Content.Paragraphs.Add(ref missing); para2.Range.Text = "Para 2 text"; para2.Range.InsertParagraphAfter(); //表格 Table firstTable = document.Tables.Add(para1.Range, 5, 5, ref missing, ref missing); firstTable.Borders.Enable = 1; foreach (Row row in firstTable.Rows) { foreach (Cell cell in row.Cells) { //表头 if (cell.RowIndex == 1) { cell.Range.Text = "Column " + cell.ColumnIndex.ToString(); cell.Range.Font.Bold = 1; cell.Range.Font.Name = "verdana"; cell.Range.Font.Size = 10; cell.Shading.BackgroundPatternColor = WdColor.wdColorGray25; cell.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; cell.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; } //行 else { cell.Range.Text = (cell.RowIndex - 2 + cell.ColumnIndex).ToString(); } } } //保存 string fName = "c://export.docx"; document.Save(); //document.SaveAs(fName); document.Close(ref missing, ref missing, ref missing); document = null; winword.Quit(ref missing, ref missing, ref missing); winword = null; } #endregion } }