您好,登錄后才能下訂單哦!
這篇文章主要介紹“C#生成Word文件的代碼分享”,在日常操作中,相信很多人在C#生成Word文件的代碼分享問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”C#生成Word文件的代碼分享”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!
本文實例為大家分享了C#生成Word文件的具體代碼,供大家參考,具體內容如下
通過Microsoft.Office.Interop.Word生成Word文檔
1.引用類 WordReport.cs,代碼如下:
using System;using System.Collections.Generic;using System.Text;using Microsoft.Office.Interop.Word;using MSWord = Microsoft.Office.Interop.Word;using System.Reflection;using System.IO; namespace CRM.Common{ public class WordReport { private _Application wordApp = null; private _Document wordDoc = null; object unite = MSWord.WdUnits.wdStory; Object Nothing = Missing.Value; public _Application Application { get { return wordApp; } set { wordApp = value; } } public _Document Document { get { return wordDoc; } set { wordDoc = value; } } // 通過模板創建新文檔 public void CreateNewDocument(string filePath) { try { killWinWordProcess(); wordApp = new ApplicationClass(); wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone; wordApp.Visible = false; object missing = System.Reflection.Missing.Value; object templateName = filePath; wordDoc = wordApp.Documents.Open(ref templateName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); } catch (Exception ex) { } } public void CreateNewDocument() { try { //killWinWordProcess(); wordApp = new ApplicationClass(); wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone; wordApp.Visible = false; Object Nothing = Missing.Value; wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing); } catch (Exception ex) { } } // 保存新文件 public void SaveDocument(string filePath) { if (File.Exists((string)filePath)) { File.Delete((string)filePath); } object fileName = filePath; object format = WdSaveFormat.wdFormatDocument;//保存格式 object miss = System.Reflection.Missing.Value; wordDoc.SaveAs(ref fileName, ref format, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss); //關閉wordDoc,wordApp對象 object SaveChanges = WdSaveOptions.wdSaveChanges; object OriginalFormat = WdOriginalFormat.wdOriginalDocumentFormat; object RouteDocument = false; wordDoc.Close(ref SaveChanges, ref OriginalFormat, ref RouteDocument); wordApp.Quit(ref SaveChanges, ref OriginalFormat, ref RouteDocument); } public void InsertText(string strContent) { //寫入普通文本 wordDoc.Content.InsertAfter(strContent); wordApp.Selection.EndKey(ref unite, ref Nothing); //將光標移動到文檔末尾 } public void InsertTitle(string strContent) { //寫入普通文本 wordApp.Selection.EndKey(ref unite, ref Nothing); //將光標移動到文檔末尾 try { wordDoc.Paragraphs.Last.Range.set_Style("標題 5"); } catch (Exception ex) { wordDoc.Paragraphs.Last.Range.set_Style("Heading 5"); } wordDoc.Paragraphs.Last.Range.Font.Color = MSWord.WdColor.wdColorBlack; wordDoc.Paragraphs.Last.Range.Font.Size = 11; wordDoc.Paragraphs.Last.Range.Font.Name = "宋體"; wordDoc.Paragraphs.Last.Range.Text = strContent; wordApp.Selection.EndKey(ref unite, ref Nothing); //將光標移動到文檔末尾 try { wordDoc.Paragraphs.Last.Range.set_Style("Normal"); } catch (Exception ex) { wordDoc.Paragraphs.Last.Range.set_Style("正文"); } } // 在書簽處插入值 public bool InsertValue(string bookmark, string value) { object bkObj = bookmark; if (wordApp.ActiveDocument.Bookmarks.Exists(bookmark)) { wordApp.ActiveDocument.Bookmarks.get_Item(ref bkObj).Select(); wordApp.Selection.TypeText(value); return true; } return false; } // 插入表格,bookmark書簽 public Table InsertTable(string bookmark, int rows, int columns, float width) { object miss = System.Reflection.Missing.Value; object oStart = bookmark; Range range = wordDoc.Bookmarks.get_Item(ref oStart).Range;//表格插入位置 Table newTable = wordDoc.Tables.Add(range, rows, columns, ref miss, ref miss); //設置表的格式 newTable.Borders.Enable = 1; //允許有邊框,默認沒有邊框(為0時報錯,1為實線邊框,2、3為虛線邊框,以后的數字沒試過) newTable.Borders.OutsideLineWidth = WdLineWidth.wdLineWidth050pt;//邊框寬度 if (width != 0) { newTable.PreferredWidth = width;//表格寬度 } newTable.AllowPageBreaks = false; return newTable; } // 合并單元格 表id,開始行號,開始列號,結束行號,結束列號 public void MergeCell(int n, int row1, int column1, int row2, int column2) { wordDoc.Content.Tables[n].Cell(row1, column1).Merge(wordDoc.Content.Tables[n].Cell(row2, column2)); } // 合并單元格 表名,開始行號,開始列號,結束行號,結束列號 public void MergeCell(Microsoft.Office.Interop.Word.Table table, int row1, int column1, int row2, int column2) { table.Cell(row1, column1).Merge(table.Cell(row2, column2)); } // 設置表格內容對齊方式 Align水平方向,Vertical垂直方向(左對齊,居中對齊,右對齊分別對應Align和Vertical的值為-1,0,1)Microsoft.Office.Interop.Word.Table table public void SetParagraph_Table(int n, int Align, int Vertical) { switch (Align) { case -1: wordDoc.Content.Tables[n].Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; break;//左對齊 case 0: wordDoc.Content.Tables[n].Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; break;//水平居中 case 1: wordDoc.Content.Tables[n].Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight; break;//右對齊 } switch (Vertical) { case -1: wordDoc.Content.Tables[n].Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalTop; break;//頂端對齊 case 0: wordDoc.Content.Tables[n].Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; break;//垂直居中 case 1: wordDoc.Content.Tables[n].Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalBottom; break;//底端對齊 } } // 設置單元格內容對齊方式 public void SetParagraph_Table(int n, int row, int column, int Align, int Vertical) { switch (Align) { case -1: wordDoc.Content.Tables[n].Cell(row, column).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; break;//左對齊 case 0: wordDoc.Content.Tables[n].Cell(row, column).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; break;//水平居中 case 1: wordDoc.Content.Tables[n].Cell(row, column).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight; break;//右對齊 } switch (Vertical) { case -1: wordDoc.Content.Tables[n].Cell(row, column).Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalTop; break;//頂端對齊 case 0: wordDoc.Content.Tables[n].Cell(row, column).Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; break;//垂直居中 case 1: wordDoc.Content.Tables[n].Cell(row, column).Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalBottom; break;//底端對齊 } } // 設置表格字體 public void SetFont_Table(Microsoft.Office.Interop.Word.Table table, string fontName, double size) { if (size != 0) { table.Range.Font.Size = Convert.ToSingle(size); } if (fontName != "") { table.Range.Font.Name = fontName; } } // 設置單元格字體 public void SetFont_Table(int n, int row, int column, string fontName, double size, int bold) { if (size != 0) { wordDoc.Content.Tables[n].Cell(row, column).Range.Font.Size = Convert.ToSingle(size); } if (fontName != "") { wordDoc.Content.Tables[n].Cell(row, column).Range.Font.Name = fontName; } wordDoc.Content.Tables[n].Cell(row, column).Range.Font.Bold = bold;// 0 表示不是粗體,其他值都是 } // 是否使用邊框,n表格的序號,use是或否 // 該處邊框參數可以用int代替bool可以讓方法更全面 // 具體值方法中介紹 public void UseBorder(int n, bool use) { if (use) { wordDoc.Content.Tables[n].Borders.Enable = 1; //允許有邊框,默認沒有邊框(為0時無邊框,1為實線邊框,2、3為虛線邊框,以后的數字沒試過) } else { wordDoc.Content.Tables[n].Borders.Enable = 0; } } // 給表格插入一行,n表格的序號從1開始記 public void AddRow(int n) { object miss = System.Reflection.Missing.Value; wordDoc.Content.Tables[n].Rows.Add(ref miss); } // 給表格添加一行 public void AddRow(Microsoft.Office.Interop.Word.Table table) { object miss = System.Reflection.Missing.Value; table.Rows.Add(ref miss); } // 給表格插入rows行,n為表格的序號 public void AddRow(int n, int rows) { object miss = System.Reflection.Missing.Value; Microsoft.Office.Interop.Word.Table table = wordDoc.Content.Tables[n]; for (int i = 0; i < rows; i++) { table.Rows.Add(ref miss); } } // 刪除表格第rows行,n為表格的序號 public void DeleteRow(int n, int row) { Microsoft.Office.Interop.Word.Table table = wordDoc.Content.Tables[n]; table.Rows[row].Delete(); } // 給表格中單元格插入元素,table所在表格,row行號,column列號,value插入的元素 public void InsertCell(Microsoft.Office.Interop.Word.Table table, int row, int column, string value) { table.Cell(row, column).Range.Text = value; } // 給表格中單元格插入元素,n表格的序號從1開始記,row行號,column列號,value插入的元素 public void InsertCell(int n, int row, int column, string value) { wordDoc.Content.Tables[n].Cell(row, column).Range.Text = value; } // 給表格插入一行數據,n為表格的序號,row行號,columns列數,values插入的值 public void InsertCell(int n, int row, int columns, string[] values) { Microsoft.Office.Interop.Word.Table table = wordDoc.Content.Tables[n]; for (int i = 0; i < columns; i++) { table.Cell(row, i + 1).Range.Text = values[i]; } } // 插入圖片 public void InsertPicture(string bookmark, string picturePath, float width, float hight) { object miss = System.Reflection.Missing.Value; object oStart = bookmark; Object linkToFile = false; //圖片是否為外部鏈接 Object saveWithDocument = true; //圖片是否隨文檔一起保存 object range = wordDoc.Bookmarks.get_Item(ref oStart).Range;//圖片插入位置 wordDoc.InlineShapes.AddPicture(picturePath, ref linkToFile, ref saveWithDocument, ref range); wordDoc.Application.ActiveDocument.InlineShapes[1].Width = width; //設置圖片寬度 wordDoc.Application.ActiveDocument.InlineShapes[1].Height = hight; //設置圖片高度 } public void InsertPicture(string picturePath, float width, float hight,WdParagraphAlignment align) { object unite = MSWord.WdUnits.wdStory; Object Nothing = Missing.Value; Application.Selection.EndKey(ref unite, ref Nothing); //將光標移動到文檔末尾 //要向Word文檔中插入圖片的位置 Object range = wordDoc.Paragraphs.Last.Range; //定義該插入的圖片是否為外部鏈接 Object linkToFile = false; //默認,這里貌似設置為bool類型更清晰一些 //定義要插入的圖片是否隨Word文檔一起保存 Object saveWithDocument = true; //默認 //使用InlineShapes.AddPicture方法(【即“嵌入型”】)插入圖片 InlineShape shape = wordDoc.InlineShapes.AddPicture(picturePath, ref linkToFile, ref saveWithDocument, ref range); wordApp.Selection.ParagraphFormat.Alignment = align;// //設置圖片寬高的絕對大小 if (width!=-1) wordDoc.InlineShapes[1].Width = width; if(hight!=-1) wordDoc.InlineShapes[1].Height = hight; try { wordDoc.Paragraphs.Last.Range.set_Style("正文"); } catch(Exception ex) { wordDoc.Paragraphs.Last.Range.set_Style("Normal"); } shape.Borders.Enable = 12; //shape.ConvertToShape().WrapFormat.Type = MSWord.WdWrapType.wdWrapSquare;//四周環繞的方式 } // 插入一段文字,text為文字內容 public void InsertText(string bookmark, string text) { object oStart = bookmark; object range = wordDoc.Bookmarks.get_Item(ref oStart).Range; Paragraph wp = wordDoc.Content.Paragraphs.Add(ref range); wp.Format.SpaceBefore = 6; wp.Range.Text = text; wp.Format.SpaceAfter = 24; wp.Range.InsertParagraphAfter(); wordDoc.Paragraphs.Last.Range.Text = "\n"; } // 殺掉winword.exe進程 public void killWinWordProcess() { System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName("WINWORD"); foreach (System.Diagnostics.Process process in processes) { bool b = process.MainWindowTitle == ""; if (process.MainWindowTitle == "") { process.Kill(); } } } internal void InsertTable(int tableRow, int tableColumn,List<string> imagePaths) { wordApp.Selection.EndKey(ref unite, ref Nothing); //將光標移動到文檔末尾 MSWord.Table table = wordDoc.Tables.Add(wordApp.Selection.Range, tableRow, tableColumn, ref Nothing, ref Nothing); //默認創建的表格沒有邊框,這里修改其屬性,使得創建的表格帶有邊框 table.Borders.Enable = 0;//這個值可以設置得很大,例如5、13等等 //表格的索引是從1開始的。 for (int i = 1; i <= tableRow; i++) { for (int j = 1; j <= tableColumn; j++) { int index = (i-1) * tableColumn + j-1; if (index < imagePaths.Count)//有文件 { string FileName = imagePaths[index]; //圖片所在路徑 object LinkToFile = false; object SaveWithDocument = true; object Anchor = table.Cell(i, j).Range;//選中要添加圖片的單元格 MSWord.InlineShape il = wordDoc.Application.ActiveDocument.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor); //圖片大小 il.Width = 100;//圖片寬度 il.Height = 100;//圖片高度 table.Rows[i].Cells[j].Split(2, 1); table.Cell(i+1, j).Range.Text = "圖片名稱:"+(index+1).ToString(); // table.Cell(i+1, j).Merge(table.Cell(i, j));//縱向合并 } } } //設置table樣式 table.Rows.HeightRule = MSWord.WdRowHeightRule.wdRowHeightAtLeast;//高度規則是:行高有最低值下限? table.Rows.Height = wordApp.CentimetersToPoints(float.Parse("0.8"));// table.Range.Font.Size = 10.5F; table.Range.Font.Bold = 0; table.Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;//表格文本居中 table.Range.Cells.VerticalAlignment = MSWord.WdCellVerticalAlignment.wdCellAlignVerticalBottom;//文本垂直貼到底部 //設置table邊框樣式 table.Borders.OutsideLineStyle = MSWord.WdLineStyle.wdLineStyleNone;//表格外框是雙線 table.Borders.InsideLineStyle = MSWord.WdLineStyle.wdLineStyleNone;//表格內框是單線 table.Rows[1].Range.Font.Bold = 1;//加粗 table.Rows[1].Range.Font.Size = 12F; table.Cell(1, 1).Range.Font.Size = 10.5F; } }}
2.生成Word文檔
/// <summary>/// /// </summary>/// <param name="path">like string path=@"c:\\temp\\"</param>public void GengerateWord(string path) { string fileName = "test.doc"; WordReport report = new WordReport(); report.CreateNewDocument(); //創建文件 report.InsertTitle("標題"); float width = 420;//圖片寬度 float height = 200;//圖片高度 report.InsertPicture("圖片地址", width, height, WdParagraphAlignment.wdAlignParagraphCenter); report.SaveDocument(path+ fileName);}
到此,關于“C#生成Word文件的代碼分享”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續學習更多相關知識,請繼續關注億速云網站,小編會繼續努力為大家帶來更多實用的文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。