C#使用模板文件批量导出word文档
生活随笔
收集整理的這篇文章主要介紹了
C#使用模板文件批量导出word文档
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
需求背景
? ? ? ? 因為疫情爆發,進入一級響應狀態,公安部門進行了嚴格出入境管理,需要對每個出入境的人進行狀態跟蹤。
? ? ? ? 疫情專班會將出入境的每個人員匯總在一張Excel表中,如下圖所示:
?
?
? ? ? ? ?每一行對應一個人員信息,一個人員信息需要生成一個協查函,需要將人員信息填入到固定格式的協查函中,協查函的格式如下圖所示:
?
功能實現?
? ? ? ? 功能實現分成兩個部分,一是從Excel讀取數據,二是將讀取的數據批量輸出到Word文檔。
從Excel讀取數據使用NPOI,輸出到word文檔使用Microsoft Word Object Library.
NPOI可以在NuGet程序包中搜索到:
?Microsoft Word Object Library.可以在類庫中引用到。
?考慮到速度,功能用winform程序實現。
?實現效果
啟動程序時:
選擇Excel:
導入Excel:
?導出到Word:
打開Word看看:
?
?在開發之前需要對創建一個Word(dot格式)模板文件,內容格式很協查函一樣,然后再需要插入數據的地方設置書簽即可。
?
?程序代碼
ExcelHelp類用于將選中的Excel數據導入到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>/// 根據指定流文件將Excel導入到datatable中/// </summary>public virtual DataTable ExcelExportDataTable(){DataTable dt = new DataTable();OpenFileDialog fileDialog = new OpenFileDialog();fileDialog.Filter = "Excel文件|*.xls;*.xlsx";fileDialog.InitialDirectory = "E:\\";//設置默認打開路徑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數據流中的數據轉化為datatable/// </summary>/// <param name="ExcelFileStream">指定流文件</param>/// <param name="SheetIndex">導入sheet頁頁號</param>/// <param name="HeaderRowIndex">行標題行號</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();/*手動構建列名*/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");//責任人姓名table.Columns.Add(columnDutyName);DataColumn columnDutyPhone = new DataColumn("DutyPhone");//責任人電話table.Columns.Add(columnDutyPhone);DataColumn columnStatus = new DataColumn("Status");//管控狀態table.Columns.Add(columnStatus);DataColumn columnBackTime = new DataColumn("BackTime");//返回封鎖區時間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);/*構建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中無數據!");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++){//創建一個Word應用程序實例Microsoft.Office.Interop.Word._Application oWord = new Microsoft.Office.Interop.Word.Application();object oMissing = System.Reflection.Missing.Value;//設置為不可見oWord.Visible = false;//模板文件地址,debug bin 目錄下//object oTemplate = "E://template.dot";object oTemplate = System.Windows.Forms.Application.StartupPath + "\\template.dot";//以模板為基礎生成文檔Microsoft.Office.Interop.Word._Document oDoc = oWord.Documents.Add(ref oTemplate, ref oMissing, ref oMissing, ref oMissing);//聲明書簽數組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";//賦值數據到書簽的位置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;//導出的Word文件地址設置在 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);//關閉word模板oWord.Quit(ref oMissing, ref oMissing, ref oMissing);}MessageBox.Show("導出成功,生成了" + count + "個文件!");}else{MessageBox.Show("Excel中無數據!");}}} }總結
以上是生活随笔為你收集整理的C#使用模板文件批量导出word文档的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 源码包安装mysql5.6_源码包安装m
- 下一篇: 安装composer以及laravel框