using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Linq; using System.Net.Mime; using System.Reflection; using System.Text; using System.Web; using Microsoft.Office.Interop.Word; namespace MojoCube.Api.File { public class WordHelper { private Application wordApp = null; private Document wordDoc = null; public Application Application { get { return wordApp; } set { wordApp = value; } } public Document Document { get { return wordDoc; } set { wordDoc = value; } } public Table AddTableTitles(string[] Titles, string bookmarkName, int RowsCount, float Width, double FontSize, ref WordHelper wordHelper) { Table table = wordHelper.InsertTable(bookmarkName, RowsCount, Titles.Length, 0); for (int j = 0; j < Titles.Length; j++) { wordHelper.InsertCell(table, 1, j + 1, Titles[j]); } if (Width != 0) { table.Columns[1].Width = Width - 4; //table.Columns[2].Width = Width * 2 + 6; table.Columns[2].Width = Titles.Length > 3 ? Width * 5 - 10 : Width * 8 + 12; } if (FontSize != 0) { wordHelper.SetFont_Table(table, "", FontSize); } return table; } public void GenerateInfos(string[] bookMarks, double[] bookInfos, ref WordHelper wordHelper) { for (int i = 0; i < bookInfos.Length; i++) { wordHelper.InsertValue(bookMarks[i], bookInfos[i].ToString()); } } public void GenerateInfos(System.Data.DataTable dt, string bookMark, ref WordHelper wordHelper) { string[] Titles = new string[dt.Columns.Count]; string strInfos = ""; for (int i = 0; i < dt.Rows.Count; i++) { for (int j = 0; j < dt.Columns.Count; j++) { if ((j == 2) && dt.Rows[i][j].ToString() != "") //插入图片 { strInfos += Titles[j] + ":\r\n"; string[] strImgs = dt.Rows[i][j].ToString().Split(new char[] { ',' }); for (int m = 0; m < strImgs.Length; m++) { strInfos += "bookMark" + i + j + m; } strInfos += "\r\n"; } else { strInfos += Titles[j] == "" ? dt.Rows[i][j].ToString() + "\r\n" : Titles[j] + ":\r\n" + dt.Rows[i][j].ToString() + "\r\n"; } } strInfos += "\r\n"; } wordHelper.InsertText(bookMark, strInfos); //插入图片 int iNo = 1; for (int i = 0; i < dt.Rows.Count; i++) { for (int j = 0; j < dt.Columns.Count; j++) { if ((j == 2) && dt.Rows[i][j].ToString() != "") //插入图片 { string[] strImgs = dt.Rows[i][j].ToString().Split(new char[] { ',' }); for (int m = 0; m < strImgs.Length; m++) { if (!System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath(strImgs[m]))) continue; BookMark bookmarkItem = new BookMark(); bookmarkItem.Name = "bookMark" + i + j + m; Range range = FindFirst(wordDoc.Range(), bookmarkItem.Name); bookmarkItem.Range = range; wordHelper.InsertBookMark(bookmarkItem); wordHelper.InsertPicture(range, HttpContext.Current.Server.MapPath(strImgs[m]), 260, 195, iNo++); Range rangeTmp = FindFirst(wordDoc.Range(), bookmarkItem.Name); if (rangeTmp != null) { rangeTmp.Select(); wordApp.Selection.Delete(); } } } } } } public Range FindFirst(Range range, string findText) { int start = range.Start; int end = range.End; bool isOk = range.Find.Execute(FindText: findText, MatchCase: true); if (isOk) { var newRange = range.Document.Range(range.Start, range.End); range.SetRange(start, end); return newRange; } else return null; } public List FindAll(Range range, string findText) { int start = range.Start; int end = range.End; List ranges = new List(); range.Find.Execute(FindText: findText, MatchCase: true); while (range.Find.Found) { //搜索会改变range,这里做了一个超出范围的判断 if (range.Start > end) break; ranges.Add(range.Document.Range(range.Start, range.End)); range.Find.Execute(FindText: findText, MatchCase: true); } //对原来的range还原 range.SetRange(start, end); return ranges; } public void GenerateTables(System.Data.DataTable dt, string bookMark, ref WordHelper wordHelper) { string[] Titles = new string[dt.Columns.Count]; for (int i = 0; i < dt.Columns.Count; i++) { if (i == 0) continue; Titles[i] = dt.Columns[i].ColumnName; } Table table = wordHelper.AddTableTitles(Titles, bookMark, dt.Rows.Count + 1, 30, 10, ref wordHelper); //填充非根节点 for (int i = 0; i < dt.Rows.Count; i++) { for (int j = 0; j < dt.Columns.Count; j++) { //if (j >= 7) break; if ((j == 2 || j == 4) && dt.Rows[i][j].ToString() != "") //插入图片 { object range = table.Cell(i + 2, j + 1).Range; string[] strImgs = dt.Rows[i][j].ToString().Split(new char[] { ',' }); for (int m = 0; m < strImgs.Length; m++) { wordHelper.InsertPicture(range, System.Web.HttpContext.Current.Server.MapPath(strImgs[m]), 70, 50, 1); } } else { wordHelper.InsertCell(table, i + 2, j + 1, dt.Rows[i][j].ToString()); } } } } /// /// 通过模板创建新文档 /// /// public void CreateNewDocument(string filePath, bool Orient) { killWinWordProcess(); wordApp = new ApplicationClass(); wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone; wordApp.Visible = false; object missing = System.Reflection.Missing.Value; object templateName = filePath; wordDoc = wordApp.Documents.Add(ref templateName, ref missing, ref missing, ref missing); wordDoc.SpellingChecked = false;//关闭拼写检查 wordDoc.ShowSpellingErrors = false; //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); if (Orient) { //设置为横向 //wordApp.Selection.PageSetup.Orientation = Microsoft.Office.Interop.Word.WdOrientation.wdOrientLandscape; //页眉右对齐+页脚居中对齐 wordApp.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageHeader; wordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;//设置右对齐 wordApp.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageFooter; wordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;//设置居中对齐 wordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument; } } /// /// 保存新文件 /// /// public void SaveDocument(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 bool InsertValue(string bookmark, string value, bool FontBold = false) { object bkObj = bookmark; if (wordApp.ActiveDocument.Bookmarks.Exists(bookmark)) { wordApp.ActiveDocument.Bookmarks.get_Item(ref bkObj).Select(); if (FontBold)//如果需要就加粗 { wordApp.Selection.Font.Bold = 1; } wordApp.Selection.TypeText(value); return true; } return false; } /// /// 插入表格,bookmark书签 /// /// /// /// /// /// public Table InsertTable(string bookmark, int rows, int columns, float width) { object miss = 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; } /// /// 合并单元格 表名,开始行号,开始列号,结束行号,结束列号 /// /// /// /// /// /// 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) /// /// /// /// public void SetParagraph_Table(Microsoft.Office.Interop.Word.Table table, int Align, int Vertical) { switch (Align) { case -1: table.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; break; //左对齐 case 0: table.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; break; //水平居中 case 1: table.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight; break; //右对齐 } switch (Vertical) { case -1: table.Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalTop; break; //顶端对齐 case 0: table.Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; break; //垂直居中 case 1: table.Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalBottom; break; //底端对齐 } } /// /// 设置表格字体 /// /// /// /// public void SetFont_Table(Table table, string fontName, double size) { if (size != 0) { table.Range.Font.Size = Convert.ToSingle(size); } if (fontName != "") { table.Range.Font.Name = fontName; } } //是否使用边框,n表格的序号,use是或否 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 = 2; //允许有边框,默认没有边框(为0时无边框,1为实线边框,2、3为虚线边框,以后的数字没试过) } } /// /// 给表格插入一行,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); } } /// /// 给表格中单元格插入元素,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 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(object range, string picturePath, float width, float hight, int no) { object linkToFile = false; //图片是否为外部链接 object saveWithDocument = true; //图片是否随文档一起保存 wordDoc.InlineShapes.AddPicture(picturePath, ref linkToFile, ref saveWithDocument, ref range); if (width != 0) { wordDoc.Application.ActiveDocument.InlineShapes[no].Width = width; //设置图片宽度 } if (hight != 0) { wordDoc.Application.ActiveDocument.InlineShapes[no].Height = hight; //设置图片高度 } } /// /// 插入一段文字,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"; } public void InsertBookMark(Bookmark bookMark) { //KillWordProcess(); if (wordApp == null) return; //存在则先删除 if (wordDoc.Bookmarks.Exists(bookMark.Name)) { DeleteBookMark(bookMark); } //object what = WdGoToItem.wdGoToBookmark; object range = wordApp.Selection.Range; //object range = wordDoc.ActiveWindow.Selection.GoTo(ref what, ref Nothing, ref Nothing, ref BookMarkName); wordDoc.Bookmarks.Add(bookMark.Name, ref range); } public void DeleteBookMark(Bookmark bookMark) { if (wordDoc.Bookmarks.Exists(bookMark.Name)) { var bookMarks = wordDoc.Bookmarks; for (int i = 1; i <= bookMarks.Count; i++) { object index = i; var mark = bookMarks.get_Item(ref index); if (mark.Name == bookMark.Name) { mark.Delete(); break; } } } } public void ReplaceBookMarkContext(IList bookMarks) { if (bookMarks == null) return; object missing = System.Reflection.Missing.Value; foreach (Bookmark bookMark in bookMarks) { if (GoToBookMark(bookMark.Name))//如果书签存在 { object oStart = bookMark.Name;//word中的书签名 //Range range = wordDoc.Bookmarks.get_Item(ref oStart).Range;//表格插入位置 //ParagraphBookMarkParam param = bookMark.Content as ParagraphBookMarkParam; //if (param == null) //{ // throw new Exception("书签参数为空"); //} //range.Text = (string)param.Context;//在书签处插入文字内容 } else { throw new Exception("书签:" + bookMark.Name + "不存在"); } } //保存word //object format = WdSaveFormat.wdFormatDocument;//保存格式 //关闭wordDoc,wordApp对象 //_saveChanges = WdSaveOptions.wdSaveChanges; //_originalFormat = WdOriginalFormat.wdOriginalDocumentFormat; //_routeDocument = false; // _wordDoc.SaveAs(ref _saveAsFilePathName, ref format, 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); } /// /// 光标移动到指定书签位置,书签不存在时不移动 /// /// /// public bool GoToBookMark(string bookMarkName) { object missing = System.Reflection.Missing.Value; //是否存在书签 if (wordDoc.Bookmarks.Exists(bookMarkName)) { object what = WdGoToItem.wdGoToBookmark; object name = bookMarkName; GoTo(what, missing, missing, name); return true; } return false; } public void GoTo(object what, object which, object count, object name) { wordApp.Selection.GoTo(ref what, ref which, ref count, ref name); } /// /// 插入一行 /// public void InsertLine(bool InsertLine) { //移动焦点并换行 object count = 1; object WdLine = WdUnits.wdLine;//换一行; Object Nothing = System.Reflection.Missing.Value; wordApp.Selection.MoveDown(ref WdLine, ref count, ref Nothing);//移动焦点 if (InsertLine) { wordApp.Selection.TypeParagraph(); //插入段落 } } /// /// word转pdf /// /// /// public bool WordToPDF(string sourcePath) { bool result = false; Application application = new Application(); Document document = null; try { application.Visible = false; document = application.Documents.Open(sourcePath); string PDFPath = sourcePath.Replace(".doc", ".pdf");//pdf存放位置 if (!System.IO.File.Exists(@PDFPath))//存在PDF,不需要继续转换 { document.ExportAsFixedFormat(PDFPath, WdExportFormat.wdExportFormatPDF); } result = true; } catch (Exception e) { Console.WriteLine(e.Message); result = false; } finally { document.Close(); } return result; } /// /// 杀掉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 class BookMark : Bookmark { public string Name { get; set; } public Range Range { get; set; } public int Start { get; set; } public int End { get; set; } public bool Empty { get; set; } public bool Column { get; set; } public int Creator { get; set; } public dynamic Parent { get; set; } public Application Application { get; set; } public WdStoryType StoryType { get; set; } public Bookmark Copy(string Info) { return this; } public void Select() { } public void Delete() { } } }