C#使用模板文件批量导出word文档
需求背景
? ? ? ? 因?yàn)橐咔楸l(fā),進(jìn)入一級響應(yīng)狀態(tài),公安部門進(jìn)行了嚴(yán)格出入境管理,需要對每個(gè)出入境的人進(jìn)行狀態(tài)跟蹤。
? ? ? ? 疫情專班會將出入境的每個(gè)人員匯總在一張Excel表中,如下圖所示:
?
?
? ? ? ? ?每一行對應(yīng)一個(gè)人員信息,一個(gè)人員信息需要生成一個(gè)協(xié)查函,需要將人員信息填入到固定格式的協(xié)查函中,協(xié)查函的格式如下圖所示:
?
功能實(shí)現(xiàn)?
? ? ? ? 功能實(shí)現(xiàn)分成兩個(gè)部分,一是從Excel讀取數(shù)據(jù),二是將讀取的數(shù)據(jù)批量輸出到Word文檔。
從Excel讀取數(shù)據(jù)使用NPOI,輸出到word文檔使用Microsoft Word Object Library.
NPOI可以在NuGet程序包中搜索到:
?Microsoft Word Object Library.可以在類庫中引用到。
?考慮到速度,功能用winform程序?qū)崿F(xiàn)。
?實(shí)現(xiàn)效果
啟動(dòng)程序時(shí):
選擇Excel:
導(dǎo)入Excel:
?導(dǎo)出到Word:
打開Word看看:
?
?在開發(fā)之前需要對創(chuàng)建一個(gè)Word(dot格式)模板文件,內(nèi)容格式很協(xié)查函一樣,然后再需要插入數(shù)據(jù)的地方設(shè)置書簽即可。
?
?程序代碼
ExcelHelp類用于將選中的Excel數(shù)據(jù)導(dǎo)入到datatable中。
using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms;namespace WindowsFormsApp1 {public class ExcelHelp{/// <summary>/// 根據(jù)指定流文件將Excel導(dǎo)入到datatable中/// </summary>public virtual DataTable ExcelExportDataTable(){DataTable dt = new DataTable();OpenFileDialog fileDialog = new OpenFileDialog();fileDialog.Filter = "Excel文件|*.xls;*.xlsx";fileDialog.InitialDirectory = "E:\\";//設(shè)置默認(rèn)打開路徑if (fileDialog.ShowDialog() == DialogResult.OK){string fileName = fileDialog.FileName;//得到文件所在位置FileStream fs = new FileStream(fileDialog.FileName, FileMode.Open, FileAccess.Read);dt = ExcelToDataTable(fs, 0, 2);}return dt;}/// <summary>/// 將excel數(shù)據(jù)流中的數(shù)據(jù)轉(zhuǎn)化為datatable/// </summary>/// <param name="ExcelFileStream">指定流文件</param>/// <param name="SheetIndex">導(dǎo)入sheet頁頁號</param>/// <param name="HeaderRowIndex">行標(biāo)題行號</param>/// <returns></returns>private DataTable ExcelToDataTable(Stream ExcelFileStream, int SheetIndex, int HeaderRowIndex){//HSSFWorkbook workbook = new HSSFWorkbook(ExcelFileStream);//IWorkbook workbook = new HSSFWorkbook(ExcelFileStream);IWorkbook workbook = new XSSFWorkbook(ExcelFileStream);ISheet sheet = workbook.GetSheetAt(SheetIndex);DataTable table = new DataTable();/*手動(dòng)構(gòu)建列名*/IRow headerRow = sheet.GetRow(HeaderRowIndex);int cellCount = headerRow.LastCellNum;DataColumn columnNo = new DataColumn("No");table.Columns.Add(columnNo);DataColumn columnName = new DataColumn("Name");//姓名table.Columns.Add(columnName);DataColumn columnID = new DataColumn("ID");//身份證table.Columns.Add(columnID);DataColumn columnPhone = new DataColumn("Phone");//電話table.Columns.Add(columnPhone);DataColumn columnStreet = new DataColumn("Street");//電話table.Columns.Add(columnStreet);DataColumn columnXVillage = new DataColumn("XVillage");//行政村table.Columns.Add(columnXVillage);DataColumn columnZVillage = new DataColumn("ZVillage");//自然村table.Columns.Add(columnZVillage);DataColumn columnAddress = new DataColumn("Address");//具體地址table.Columns.Add(columnAddress);DataColumn columnDutyName = new DataColumn("DutyName");//責(zé)任人姓名table.Columns.Add(columnDutyName);DataColumn columnDutyPhone = new DataColumn("DutyPhone");//責(zé)任人電話table.Columns.Add(columnDutyPhone);DataColumn columnStatus = new DataColumn("Status");//管控狀態(tài)table.Columns.Add(columnStatus);DataColumn columnBackTime = new DataColumn("BackTime");//返回封鎖區(qū)時(shí)間table.Columns.Add(columnBackTime);DataColumn columnProvince = new DataColumn("Province");//省table.Columns.Add(columnProvince);DataColumn columnCity = new DataColumn("City");//市table.Columns.Add(columnCity);DataColumn columnCountry = new DataColumn("Country");//村table.Columns.Add(columnCountry);DataColumn columnAddress2 = new DataColumn("Address2");//具體地址table.Columns.Add(columnAddress2);/*構(gòu)建datatable表體*/int firstRowNum = 3;//int rowCount = sheet.LastRowNum;for (int i = firstRowNum; i <= sheet.LastRowNum; i++){IRow row = sheet.GetRow(i);DataRow dataRow = table.NewRow();for (int j = row.FirstCellNum; j < cellCount; j++){if (row.GetCell(j) != null){dataRow[j] = row.GetCell(j).ToString();}}table.Rows.Add(dataRow);}ExcelFileStream.Close();workbook = null;sheet = null;return table;}} } using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Microsoft.Office.Interop.Word;namespace WindowsFormsApp1 {public partial class Form1 : Form{public System.Data.DataTable table;public Form1(){InitializeComponent();}private void button1_Click(object sender, EventArgs e){ExcelHelp eh = new ExcelHelp();table = eh.ExcelExportDataTable();dataGridView1.AllowUserToAddRows = false;dataGridView1.DataSource = table;if (table.Rows.Count == 0){MessageBox.Show("Excel中無數(shù)據(jù)!");return;}}private void button2_Click(object sender, EventArgs e){if (table == null){MessageBox.Show("請先選擇Excel!");return;}int count = table.Rows.Count;//Microsoft.Office.Interop.Word._Application oWord;if (count > 0){for (int i = 0; i < count; i++){//創(chuàng)建一個(gè)Word應(yīng)用程序?qū)嵗齅icrosoft.Office.Interop.Word._Application oWord = new Microsoft.Office.Interop.Word.Application();object oMissing = System.Reflection.Missing.Value;//設(shè)置為不可見oWord.Visible = false;//模板文件地址,debug bin 目錄下//object oTemplate = "E://template.dot";object oTemplate = System.Windows.Forms.Application.StartupPath + "\\template.dot";//以模板為基礎(chǔ)生成文檔Microsoft.Office.Interop.Word._Document oDoc = oWord.Documents.Add(ref oTemplate, ref oMissing, ref oMissing, ref oMissing);//聲明書簽數(shù)組object[] oBookMark = new object[8];//賦值書簽名oBookMark[0] = "Name";oBookMark[1] = "ID";oBookMark[2] = "Phone";oBookMark[3] = "City";oBookMark[4] = "Country";oBookMark[5] = "Address2";oBookMark[6] = "MM";oBookMark[7] = "DD";//賦值數(shù)據(jù)到書簽的位置string mm = DateTime.Now.Month.ToString();string dd = DateTime.Now.Day.ToString();oDoc.Bookmarks.get_Item(ref oBookMark[0]).Range.Text = table.Rows[i]["Name"].ToString();oDoc.Bookmarks.get_Item(ref oBookMark[1]).Range.Text = table.Rows[i]["ID"].ToString();oDoc.Bookmarks.get_Item(ref oBookMark[2]).Range.Text = table.Rows[i]["Phone"].ToString();oDoc.Bookmarks.get_Item(ref oBookMark[3]).Range.Text = table.Rows[i]["City"].ToString();oDoc.Bookmarks.get_Item(ref oBookMark[4]).Range.Text = table.Rows[i]["Country"].ToString();oDoc.Bookmarks.get_Item(ref oBookMark[5]).Range.Text = table.Rows[i]["Address2"].ToString();oDoc.Bookmarks.get_Item(ref oBookMark[6]).Range.Text = mm;oDoc.Bookmarks.get_Item(ref oBookMark[7]).Range.Text = dd;//導(dǎo)出的Word文件地址設(shè)置在 debug bin里的NewFile文件夾object path = System.Windows.Forms.Application.StartupPath + "\\NewFile\\" + filename + ".doc";oDoc.SaveAs(ref path, ref oMissing, ref oMissing, ref oMissing,ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,ref oMissing, ref oMissing);oDoc.Close(ref oMissing, ref oMissing, ref oMissing);//關(guān)閉word模板oWord.Quit(ref oMissing, ref oMissing, ref oMissing);}MessageBox.Show("導(dǎo)出成功,生成了" + count + "個(gè)文件!");}else{MessageBox.Show("Excel中無數(shù)據(jù)!");}}} }總結(jié)
以上是生活随笔為你收集整理的C#使用模板文件批量导出word文档的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 源码包安装mysql5.6_源码包安装m
- 下一篇: C#中其他简单LINQ查询表达式的简单使