C# 使用Word模板導(dǎo)出數(shù)據(jù)的實(shí)現(xiàn)代碼
使用NPOI控件導(dǎo)出數(shù)據(jù)到Word模板中方式:
效果如下:
Word模板:
運(yùn)行結(jié)果:
實(shí)現(xiàn)如下:
Student.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ExportWord { public class Student { public String Photo { get; set; } public FileStream PhotoData { get; set; } public String Name { get; set; } public List<Course> Data { get; set; } } }
Course.cs
using System; namespace ExportWord { public class Course { public String Name { get; set; } public Int32 Score { get; set; } } }
Main.cs
public FileStream Export() { Student stu = new ExportWord.Student(); stu.Name = "AAAAA"; stu.Photo = @"C:\Users\hutao\Pictures\2019-12-16_153943.png"; stu.PhotoData = new FileStream(stu.Photo, FileMode.Open, FileAccess.Read); stu.Data = new List<Course>(); stu.Data.Add(new ExportWord.Course() { Name = "BBBB", Score = 89 }); stu.Data.Add(new ExportWord.Course() { Name = "CCCC", Score = 90 }); stu.Data.Add(new ExportWord.Course() { Name = "DDDD", Score = 100 }); stu.Data.Add(new ExportWord.Course() { Name = "EEEE", Score = 101 }); stu.Data.Add(new ExportWord.Course() { Name = "FFFF", Score = 102 }); stu.Data.Add(new ExportWord.Course() { Name = "GGGG", Score = 103 }); string path = Application.StartupPath; string filepath = (path + @"\template.docx"); using (FileStream stream = File.OpenRead(filepath)) { XWPFDocument doc = new XWPFDocument(stream); //遍歷段落 foreach (var para in doc.Paragraphs) { ReplaceKey(para, stu); } //遍歷表格 var tables = doc.Tables; foreach (var table in tables) { ReplaceTableKey(table, stu.Data, "Data"); } foreach (var table in tables) { foreach (var row in table.Rows) { foreach (var cell in row.GetTableCells()) { foreach (var para in cell.Paragraphs) { ReplaceKey(para, stu); } } } } FileStream out1 = new FileStream(path + @"\123.docx", FileMode.Create); doc.Write(out1); out1.Close(); return out1; } }
ReplaceKey()
/// <summary> /// 替換Key /// </summary> /// <param name="para"></param> /// <param name="model"></param> private static void ReplaceKey(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) { if (p.PropertyType.Name == "FileStream") { if (text.Contains("$" + p.Name + "$")) { runs[i].SetText("", 0); runs[i].AddPicture((FileStream)p.GetValue(model, null), (int)PictureType.JPEG, "image1", 1000000, 1000000); } } else { //$$與模板中$$對(duì)應(yīng),也可以改成其它符號(hào),比如{$name},務(wù)必做到唯一 if (text.Contains("$" + p.Name + "$")) { text = text.Replace("$" + p.Name + "$", p.GetValue(model, null).ToString()); runs[i].SetText(text, 0); } } } } }
ReplaceTableKey()
/// <summary> /// 替換表格Key /// </summary> /// <param name="para"></param> /// <param name="model"></param> private static void ReplaceTableKey(XWPFTable table, IList list, String field) { List<XWPFParagraph> paras = new List<XWPFParagraph>(); // 獲取最后一行數(shù)據(jù),最后一行設(shè)置值 Int32 iLastRowIndex = 0; for (int iIndex = 0; iIndex < table.Rows.Count; iIndex++) { if (iIndex == table.Rows.Count - 1) { iLastRowIndex = iIndex; foreach (var cell in table.Rows[iIndex].GetTableCells()) { foreach (var para in cell.Paragraphs) { paras.Add(para); } } } } // 刪除最后一行 table.RemoveRow(iLastRowIndex); for (int iIndex = 0; iIndex < list.Count; iIndex++) { dynamic data = list[iIndex]; Type t = data.GetType(); PropertyInfo[] pi = t.GetProperties(); // 表增加行 XWPFTableRow m_row = table.CreateRow(); CT_Row m_NewRow = new CT_Row(); String text = String.Empty; Int32 jIndex = 0; paras.ForEach(para => { text = para.ParagraphText; foreach (PropertyInfo p in pi) { if (text.Contains("$" + field + "." + p.Name + "$")) { m_row.GetCell(jIndex).SetText(p.GetValue(data, null).ToString()); } } jIndex++; }); m_row = new XWPFTableRow(m_NewRow, table); table.AddRow(m_row); } }
protected void btn_Click(object sender, EventArgs e) { using (FileStream fs = Export()) { string path = Application.StartupPath; //將byte數(shù)組寫(xiě)入文件中 DownloadFile(fs); } } /// <summary> /// 下載文件 /// </summary> /// <param name="URL">下載文件地址</param> /// <param name="Filename">下載后另存為(全路徑)</param> private bool DownloadFile(FileStream fs) { try { byte[] by = new byte[fs.Length]; fs.Write(by, 0, by.Length); fs.Close(); return true; } catch (System.Exception e) { return false; } }
以上就是C# 使用Word模板導(dǎo)出數(shù)據(jù)的詳細(xì)內(nèi)容,更多關(guān)于C# 導(dǎo)出數(shù)據(jù)的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C#多線程學(xué)習(xí)之(二)操縱一個(gè)線程的方法
這篇文章主要介紹了C#多線程學(xué)習(xí)之操縱一個(gè)線程的方法,實(shí)例分析了C#中線程的使用技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-04-04C# 顯示、隱藏窗口對(duì)應(yīng)的任務(wù)欄
WPF中全屏窗口,會(huì)自動(dòng)隱藏任務(wù)欄,那非全屏窗口如何隱藏任務(wù)欄?甚至有沒(méi)有一種場(chǎng)景,隱藏任務(wù)后自定義一套系統(tǒng)任務(wù)欄來(lái)顯示?這篇文章主要介紹了C# 顯示、隱藏窗口對(duì)應(yīng)的任務(wù)欄,需要的朋友可以參考下2021-10-10C#交錯(cuò)數(shù)組知識(shí)點(diǎn)分析
在本篇文章里小編給大家整理的是關(guān)于C#交錯(cuò)數(shù)組知識(shí)點(diǎn)分析,需要的朋友們參考下。2019-11-11C#判斷一天、一年已經(jīng)過(guò)了百分之多少的方法
這篇文章主要介紹了C#判斷一天、一年已經(jīng)過(guò)了百分之多少的方法,涉及C#針對(duì)時(shí)間及日期的運(yùn)算與判定技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-08-08