C#生成Word文件(圖片、文字)
更新時間:2019年05月29日 15:34:12 作者:Daniel799
這篇文章主要為大家詳細介紹了C#生成Word文件,包括圖片、文字等素材,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了C#生成Word文件的具體代碼,供大家參考,具體內(nèi)容如下
通過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; } } // 通過模板創(chuàng)建新文檔 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); //關(guān)閉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); //將光標(biāo)移動到文檔末尾 } public void InsertTitle(string strContent) { //寫入普通文本 wordApp.Selection.EndKey(ref unite, ref Nothing); //將光標(biāo)移動到文檔末尾 try { wordDoc.Paragraphs.Last.Range.set_Style("標(biāo)題 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); //將光標(biāo)移動到文檔末尾 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); //設(shè)置表的格式 newTable.Borders.Enable = 1; //允許有邊框,默認沒有邊框(為0時報錯,1為實線邊框,2、3為虛線邊框,以后的數(shù)字沒試過) newTable.Borders.OutsideLineWidth = WdLineWidth.wdLineWidth050pt;//邊框?qū)挾? if (width != 0) { newTable.PreferredWidth = width;//表格寬度 } newTable.AllowPageBreaks = false; return newTable; } // 合并單元格 表id,開始行號,開始列號,結(jié)束行號,結(jié)束列號 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)); } // 合并單元格 表名,開始行號,開始列號,結(jié)束行號,結(jié)束列號 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)); } // 設(shè)置表格內(nèi)容對齊方式 Align水平方向,Vertical垂直方向(左對齊,居中對齊,右對齊分別對應(yīng)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;//底端對齊 } } // 設(shè)置單元格內(nèi)容對齊方式 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;//底端對齊 } } // 設(shè)置表格字體 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; } } // 設(shè)置單元格字體 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是或否 // 該處邊框參數(shù)可以用int代替bool可以讓方法更全面 // 具體值方法中介紹 public void UseBorder(int n, bool use) { if (use) { wordDoc.Content.Tables[n].Borders.Enable = 1; //允許有邊框,默認沒有邊框(為0時無邊框,1為實線邊框,2、3為虛線邊框,以后的數(shù)字沒試過) } 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; } // 給表格插入一行數(shù)據(jù),n為表格的序號,row行號,columns列數(shù),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; //設(shè)置圖片寬度 wordDoc.Application.ActiveDocument.InlineShapes[1].Height = hight; //設(shè)置圖片高度 } 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); //將光標(biāo)移動到文檔末尾 //要向Word文檔中插入圖片的位置 Object range = wordDoc.Paragraphs.Last.Range; //定義該插入的圖片是否為外部鏈接 Object linkToFile = false; //默認,這里貌似設(shè)置為bool類型更清晰一些 //定義要插入的圖片是否隨Word文檔一起保存 Object saveWithDocument = true; //默認 //使用InlineShapes.AddPicture方法(【即“嵌入型”】)插入圖片 InlineShape shape = wordDoc.InlineShapes.AddPicture(picturePath, ref linkToFile, ref saveWithDocument, ref range); wordApp.Selection.ParagraphFormat.Alignment = align;// //設(shè)置圖片寬高的絕對大小 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;//四周環(huán)繞的方式 } // 插入一段文字,text為文字內(nèi)容 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); //將光標(biāo)移動到文檔末尾 MSWord.Table table = wordDoc.Tables.Add(wordApp.Selection.Range, tableRow, tableColumn, ref Nothing, ref Nothing); //默認創(chuàng)建的表格沒有邊框,這里修改其屬性,使得創(chuàng)建的表格帶有邊框 table.Borders.Enable = 0;//這個值可以設(shè)置得很大,例如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));//縱向合并 } } } //設(shè)置table樣式 table.Rows.HeightRule = MSWord.WdRowHeightRule.wdRowHeightAtLeast;//高度規(guī)則是:行高有最低值下限? 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;//文本垂直貼到底部 //設(shè)置table邊框樣式 table.Borders.OutsideLineStyle = MSWord.WdLineStyle.wdLineStyleNone;//表格外框是雙線 table.Borders.InsideLineStyle = MSWord.WdLineStyle.wdLineStyleNone;//表格內(nèi)框是單線 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(); //創(chuàng)建文件 report.InsertTitle("標(biāo)題"); float width = 420;//圖片寬度 float height = 200;//圖片高度 report.InsertPicture("圖片地址", width, height, WdParagraphAlignment.wdAlignParagraphCenter); report.SaveDocument(path+ fileName); }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
淺談C#2.0泛型中的變化:default關(guān)鍵字
下面就詳細的說明一下。之所以會用到default關(guān)鍵字,是因為需要在不知道類型參數(shù)為值類型還是引用類型的情況下,為對象實例賦初值2013-09-09區(qū)分WCF與WebService的異同、優(yōu)勢
這篇文章主要幫助大家區(qū)分WCF與WebService的異同、優(yōu)勢,分為三大方面進行研究學(xué)習(xí),感興趣的小伙伴們可以參考一下2016-03-03C#執(zhí)行Javascript代碼的幾種方法總結(jié)
本篇文章主要是對C#執(zhí)行Javascript代碼的幾種方法進行了詳細的總結(jié)介紹,需要的朋友可以過來參考下,希望對大家有所幫助2014-01-01C#實現(xiàn)讀取多條數(shù)據(jù)記錄并導(dǎo)出到Word
這篇文章主要為大家詳細介紹了C#如何實現(xiàn)讀取多條數(shù)據(jù)記錄并導(dǎo)出到Word,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-03-03