private void HighlightWords() { try { if (_wordTokens == null || _wordTokens.Length == 0) { return; } Word.Range range = _document.Content; Word.Find find = range.Find; object findText = _wordTokens[0]; find.ClearFormatting(); object wordWrap = Word.WdFindWrap.wdFindContinue; bool found = find.Execute(ref findText, ref FALSE, ref TRUE, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue); if (found) { range.Select(); } } catch (Exception exception) { _tracer.TraceException(exception); } }
public void InsertBT() { object missing = System.Reflection.Missing.Value; Word._Application app = new Word.Application(); object path = RandomPath; //object fileName = @"\tmp\show.doc"; // Word.Document doc = app.Documents.Open(ref fileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); //doc.Activate(); Word.Document doc = app.Documents.Add(ref missing, ref missing, ref missing, ref missing); doc.Activate(); Word.Range range = doc.Paragraphs.Last.Range; //定位到段尾 range.Text = "脚手架专项施工方案"; range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; //文字居中 //object styleName = "标题 2"; // range.set_Style(ref styleName); range.Font.Size = 20; range.Font.Name = "黑体"; range.Font.Bold = 1; doc.SaveAs(ref path, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); app.Quit(ref missing, ref missing, ref missing); InsertFile(path.ToString()); //range.InsertParagraphAfter(); }
/// <summary> /// Determine the last header before the given range's start position. That would be the chapter the range is part of. /// </summary> /// <param name="headings">List of headings as identified in the document.</param> /// <param name="range">The current range</param> /// <returns></returns> private static string GetHeaderForRange(IEnumerable <Heading> headings, Word.Range range) { var found = (from h in headings where h.Start <= range.Start select h).LastOrDefault(); if (found != null) { return(found.Text); } return("Unknown"); }
//// ---------------------------------------------------- //// Find and replace words in MS Word //// ---------------------------------------------------- //public static void FindAndReplaceFIRST( // object vkFind, // object vkReplace, // object vkNum, // Word.Application vkWordApp, // Word.Document vkMyDoc // ) //{ // object vkReadOnly = false; // object vkVisible = true; // object vkFalse = false; // object missing = false; // object vkTrue = true; // object vkDynamic = 2; // object replaceAll = Word.WdReplace.wdReplaceAll; // if (vkMyDoc == null) // { // return; // } // if (vkWordApp == null) // { // return; // } // if (vkReplace.ToString().Trim().Length == 0) // { // return; // } // if (vkFind.ToString().Trim().Length == 0) // { // return; // } // // Replace Word Document body // // // // 05/09/2010 - Testando a passagem de paramentros com nome do parametro... nao remover codigo abaixo. // // Working... Forward = false; // //vkWordApp.Selection.Find.Execute( // // ref vkFind, ref vkFalse, ref vkFalse, // // ref vkFalse, ref vkFalse, ref vkFalse, // // ref vkTrue, ref vkNum, ref vkFalse, // // ref vkReplace, ref vkDynamic, ref vkFalse, // // ref vkFalse, ref vkFalse, ref vkFalse ); // //vkWordApp.Selection.Find.Execute( // // FindText: vkFind, // // ReplaceWith: vkReplace, // // MatchCase: vkFalse, // // MatchWholeWord: vkTrue, // // MatchAllWordForms: vkTrue, // // Replace: vkDynamic); // vkWordApp.Selection.Find.Execute( // MatchCase: vkFalse, // MatchWholeWord: vkTrue, // MatchWildcards: vkFalse, // MatchSoundsLike: vkFalse, // MatchAllWordForms: vkFalse, // Forward: vkFalse, // Wrap: vkNum, // Format: vkFalse, // FindText: vkFind, // ReplaceWith: vkReplace, // Replace: vkDynamic, // MatchKashida: vkFalse, // MatchDiacritics: vkFalse, // MatchAlefHamza: vkFalse, // MatchControl: vkFalse ); // // Replace in the primary header/ footer // // // //vkMyDoc.Sections.Item(1).Headers.Item(Word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range.Find.Execute( // // ref vkFind, ref vkFalse, ref vkFalse, // // ref vkFalse, ref vkFalse, ref vkFalse, // // ref vkTrue, ref vkNum, ref vkFalse, // // ref vkReplace, ref vkDynamic, ref vkFalse, // // ref vkFalse, ref vkFalse, ref vkFalse); // vkMyDoc.Sections.Item( 1 ).Headers.Item( Word.WdHeaderFooterIndex.wdHeaderFooterPrimary ).Range.Find.Execute( // FindText: vkFind, // MatchCase: vkFalse, // MatchWholeWord: vkFalse, // MatchWildcards: vkFalse, // MatchSoundsLike: vkFalse, // MatchAllWordForms: vkFalse, // Forward: vkFalse, // Wrap: vkNum, // Format: vkFalse, // ReplaceWith: vkReplace, // Replace: vkDynamic, // MatchKashida: vkFalse, // MatchDiacritics: vkFalse, // MatchAlefHamza: vkFalse, // MatchControl: vkFalse ); // vkMyDoc.Sections.Item( 1 ).Headers.Item( Word.WdHeaderFooterIndex.wdHeaderFooterFirstPage).Range.Find.Execute( // FindText: vkFind, // MatchCase: vkFalse, // MatchWholeWord: vkFalse, // MatchWildcards: vkFalse, // MatchSoundsLike: vkFalse, // MatchAllWordForms: vkFalse, // Forward: vkFalse, // Wrap: vkNum, // Format: vkFalse, // ReplaceWith: vkReplace, // Replace: vkDynamic, // MatchKashida: vkFalse, // MatchDiacritics: vkFalse, // MatchAlefHamza: vkFalse, // MatchControl: vkFalse ); // vkMyDoc.Sections.Item( 1 ).Headers.Item( Word.WdHeaderFooterIndex.wdHeaderFooterEvenPages).Range.Find.Execute( // FindText: vkFind, // MatchCase: vkFalse, // MatchWholeWord: vkFalse, // MatchWildcards: vkFalse, // MatchSoundsLike: vkFalse, // MatchAllWordForms: vkFalse, // Forward: vkFalse, // Wrap: vkNum, // Format: vkFalse, // ReplaceWith: vkReplace, // Replace: vkDynamic, // MatchKashida: vkFalse, // MatchDiacritics: vkFalse, // MatchAlefHamza: vkFalse, // MatchControl: vkFalse ); // // Replace in the first page footer // // // //vkMyDoc.Sections.Item( 1 ).Footers.Item( Word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range.Find.Execute( // // ref vkFind, ref vkFalse, ref vkFalse, // // ref vkFalse, ref vkFalse, ref vkFalse, // // ref vkTrue, ref vkNum, ref vkFalse, // // ref vkReplace, ref vkDynamic, ref vkFalse, // // ref vkFalse, ref vkFalse, ref vkFalse ); // vkMyDoc.Sections.Item( 1 ).Footers.Item( Word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range.Find.Execute( // FindText: vkFind, // MatchCase: vkFalse, // MatchWholeWord: vkFalse, // MatchWildcards: vkFalse, // MatchSoundsLike: vkFalse, // MatchAllWordForms: vkFalse, // Forward: vkFalse, // Wrap: vkNum, // Format: vkFalse, // ReplaceWith: vkReplace, // Replace: vkDynamic, // MatchKashida: vkFalse, // MatchDiacritics: vkFalse, // MatchAlefHamza: vkFalse, // MatchControl: vkFalse ); // vkMyDoc.Sections.Item( 1 ).Footers.Item( Word.WdHeaderFooterIndex.wdHeaderFooterFirstPage ).Range.Find.Execute( // FindText: vkFind, // MatchCase: vkFalse, // MatchWholeWord: vkFalse, // MatchWildcards: vkFalse, // MatchSoundsLike: vkFalse, // MatchAllWordForms: vkFalse, // Forward: vkFalse, // Wrap: vkNum, // Format: vkFalse, // ReplaceWith: vkReplace, // Replace: vkDynamic, // MatchKashida: vkFalse, // MatchDiacritics: vkFalse, // MatchAlefHamza: vkFalse, // MatchControl: vkFalse ); // vkMyDoc.Sections.Item( 1 ).Footers.Item( Word.WdHeaderFooterIndex.wdHeaderFooterEvenPages ).Range.Find.Execute( // FindText: vkFind, // MatchCase: vkFalse, // MatchWholeWord: vkFalse, // MatchWildcards: vkFalse, // MatchSoundsLike: vkFalse, // MatchAllWordForms: vkFalse, // Forward: vkFalse, // Wrap: vkNum, // Format: vkFalse, // ReplaceWith: vkReplace, // Replace: vkDynamic, // MatchKashida: vkFalse, // MatchDiacritics: vkFalse, // MatchAlefHamza: vkFalse, // MatchControl: vkFalse ); //} /// <summary> /// Replace inside the range /// </summary> /// <param name="range"></param> /// <param name="wordDocument"></param> /// <param name="wordApp"></param> /// <param name="findText"></param> /// <param name="replaceText"></param> private static void ReplaceRange(Word.Range range, Word.Document wordDocument, Word.Application wordApp, object findText, object replaceText) { object missing = System.Reflection.Missing.Value; wordDocument.Activate(); //object item = Word.WdGoToItem.wdGoToPage; //object whichItem = Word.WdGoToDirection.wdGoToFirst; //wordDocument.GoTo(ref item, ref whichItem, ref missing, ref missing); //object forward = true; //object replaceAll = Word.WdReplace.wdReplaceAll; //object matchAllWord = true; //range.Find.Execute(ref findText, ref missing, ref matchAllWord, // ref missing, ref missing, ref missing, ref forward, // ref missing, ref missing, ref replaceText, ref replaceAll, // ref missing, ref missing, ref missing, ref missing); range.Find.ClearFormatting(); range.Find.Replacement.ClearFormatting(); object vkTrue = true; object vkFalse = false; range.Find.Execute( FindText: findText, MatchCase: vkFalse, MatchWholeWord: vkTrue, MatchWildcards: vkFalse, MatchSoundsLike: vkFalse, MatchAllWordForms: vkFalse, Forward: vkFalse, Wrap: 1, Format: vkFalse, ReplaceWith: replaceText, Replace: 2, MatchKashida: vkFalse, MatchDiacritics: vkFalse, MatchAlefHamza: vkFalse, MatchControl: vkFalse); }
public void InsertTitle(string title, string level) { object missing = System.Reflection.Missing.Value; Word._Application app = new Word.Application(); object path = RandomPath; Word.Document doc = app.Documents.Add(ref missing, ref missing, ref missing, ref missing); doc.Activate(); Word.Range range = doc.Paragraphs.Last.Range;//定位到段尾 //range.InsertParagraphAfter(); range.Text = level + "." + title; range.Font.Italic = 1; range.Font.Color = Word.WdColor.wdColorBlue; //object styleName = "标题 3"; //range.set_Style(ref styleName); doc.SaveAs(ref path, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); app.Quit(ref missing, ref missing, ref missing); InsertFile(path.ToString()); }
private void but_Table_Click(object sender, EventArgs e) { object Nothing = System.Reflection.Missing.Value; object missing = System.Reflection.Missing.Value; //创建Word文档 Word.Application wordApp = new Word.ApplicationClass(); Word.Document wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing); wordApp.Visible = true; //设置文档宽度 wordApp.Selection.PageSetup.LeftMargin = wordApp.CentimetersToPoints(float.Parse("2")); wordApp.ActiveWindow.ActivePane.HorizontalPercentScrolled = 11; wordApp.Selection.PageSetup.RightMargin = wordApp.CentimetersToPoints(float.Parse("2")); Object start = Type.Missing; Object end = Type.Missing; PictureBox pp = new PictureBox(); //新建一个PictureBox控件 int p1 = 0; for (int i = 0; i < MyDS_Grid.Tables[0].Rows.Count; i++) { try { byte[] pic = (byte[])(MyDS_Grid.Tables[0].Rows[i][23]); //将数据库中的图片转换成二进制流 MemoryStream ms = new MemoryStream(pic); //将字节数组存入到二进制流中 pp.Image = Image.FromStream(ms); //二进制流Image控件中显示 pp.Image.Save(@"C:\22.bmp"); //将图片存入到指定的路径 } catch { p1 = 1; } object rng = Type.Missing; string strInfo = "职工基本信息表" + "(" + MyDS_Grid.Tables[0].Rows[i][1].ToString() + ")"; start = 0; end = 0; wordDoc.Range(ref start, ref end).InsertBefore(strInfo); //插入文本 wordDoc.Range(ref start, ref end).Font.Name = "Verdana"; //设置字体 wordDoc.Range(ref start, ref end).Font.Size = 20; //设置字体大小 wordDoc.Range(ref start, ref end).ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; //设置字体局中 start = strInfo.Length; end = strInfo.Length; wordDoc.Range(ref start, ref end).InsertParagraphAfter();//插入回车 object missingValue = Type.Missing; object location = strInfo.Length; //如果location超过已有字符的长度将会出错。一定要比"明细表"串多一个字符 Word.Range rng2 = wordDoc.Range(ref location, ref location); wordDoc.Tables.Add(rng2, 14, 6, ref missingValue, ref missingValue); wordDoc.Tables.Item(1).Rows.HeightRule = Word.WdRowHeightRule.wdRowHeightAtLeast; wordDoc.Tables.Item(1).Rows.Height = wordApp.CentimetersToPoints(float.Parse("0.8")); wordDoc.Tables.Item(1).Range.Font.Size = 10; wordDoc.Tables.Item(1).Range.Font.Name = "宋体"; //设置表格样式 wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderLeft).LineStyle = Word.WdLineStyle.wdLineStyleSingle; wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderLeft).LineWidth = Word.WdLineWidth.wdLineWidth050pt; wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderLeft).Color = Word.WdColor.wdColorAutomatic; wordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;//设置右对齐 //第5行显示 wordDoc.Tables.Item(1).Cell(1, 5).Merge(wordDoc.Tables.Item(1).Cell(5, 6)); //第6行显示 wordDoc.Tables.Item(1).Cell(6, 5).Merge(wordDoc.Tables.Item(1).Cell(6, 6)); //第9行显示 wordDoc.Tables.Item(1).Cell(9, 4).Merge(wordDoc.Tables.Item(1).Cell(9, 6)); //第12行显示 wordDoc.Tables.Item(1).Cell(12, 2).Merge(wordDoc.Tables.Item(1).Cell(12, 6)); //第13行显示 wordDoc.Tables.Item(1).Cell(13, 2).Merge(wordDoc.Tables.Item(1).Cell(13, 6)); //第14行显示 wordDoc.Tables.Item(1).Cell(14, 2).Merge(wordDoc.Tables.Item(1).Cell(14, 6)); //第1行赋值 wordDoc.Tables.Item(1).Cell(1, 1).Range.Text = "职工编号:"; wordDoc.Tables.Item(1).Cell(1, 2).Range.Text = MyDS_Grid.Tables[0].Rows[i][0].ToString(); wordDoc.Tables.Item(1).Cell(1, 3).Range.Text = "职工姓名:"; wordDoc.Tables.Item(1).Cell(1, 4).Range.Text = MyDS_Grid.Tables[0].Rows[i][1].ToString(); //插入图片 if (p1 == 0) { string FileName = @"C:\22.bmp";//图片所在路径 object LinkToFile = false; object SaveWithDocument = true; object Anchor = wordDoc.Tables.Item(1).Cell(1, 5).Range; //指定图片插入的区域 //将图片插入到单元格中 wordDoc.Tables.Item(1).Cell(1, 5).Range.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor); } p1 = 0; //第2行赋值 wordDoc.Tables.Item(1).Cell(2, 1).Range.Text = "民族类别:"; wordDoc.Tables.Item(1).Cell(2, 2).Range.Text = MyDS_Grid.Tables[0].Rows[i][2].ToString(); wordDoc.Tables.Item(1).Cell(2, 3).Range.Text = "出生日期:"; try { wordDoc.Tables.Item(1).Cell(2, 4).Range.Text = Convert.ToString(Convert.ToDateTime(MyDS_Grid.Tables[0].Rows[i][3]).ToShortDateString()); } catch { wordDoc.Tables.Item(1).Cell(2, 4).Range.Text = ""; } //Convert.ToString(MyDS_Grid.Tables[0].Rows[i][3]); //第3行赋值 wordDoc.Tables.Item(1).Cell(3, 1).Range.Text = "年龄:"; wordDoc.Tables.Item(1).Cell(3, 2).Range.Text = Convert.ToString(MyDS_Grid.Tables[0].Rows[i][4]); wordDoc.Tables.Item(1).Cell(3, 3).Range.Text = "文化程序:"; wordDoc.Tables.Item(1).Cell(3, 4).Range.Text = MyDS_Grid.Tables[0].Rows[i][5].ToString(); //第4行赋值 wordDoc.Tables.Item(1).Cell(4, 1).Range.Text = "婚姻:"; wordDoc.Tables.Item(1).Cell(4, 2).Range.Text = MyDS_Grid.Tables[0].Rows[i][6].ToString(); wordDoc.Tables.Item(1).Cell(4, 3).Range.Text = "性别:"; wordDoc.Tables.Item(1).Cell(4, 4).Range.Text = MyDS_Grid.Tables[0].Rows[i][7].ToString(); //第5行赋值 wordDoc.Tables.Item(1).Cell(5, 1).Range.Text = "政治面貌:"; wordDoc.Tables.Item(1).Cell(5, 2).Range.Text = MyDS_Grid.Tables[0].Rows[i][8].ToString(); wordDoc.Tables.Item(1).Cell(5, 3).Range.Text = "单位工作时间:"; try { wordDoc.Tables.Item(1).Cell(5, 4).Range.Text = Convert.ToString(Convert.ToDateTime(MyDS_Grid.Tables[0].Rows[0][10]).ToShortDateString()); } catch { wordDoc.Tables.Item(1).Cell(5, 4).Range.Text = ""; } //第6行赋值 wordDoc.Tables.Item(1).Cell(6, 1).Range.Text = "籍贯:"; wordDoc.Tables.Item(1).Cell(6, 2).Range.Text = MyDS_Grid.Tables[0].Rows[i][24].ToString(); wordDoc.Tables.Item(1).Cell(6, 3).Range.Text = MyDS_Grid.Tables[0].Rows[i][25].ToString(); wordDoc.Tables.Item(1).Cell(6, 4).Range.Text = "身份证:"; wordDoc.Tables.Item(1).Cell(6, 5).Range.Text = MyDS_Grid.Tables[0].Rows[i][9].ToString(); //第7行赋值 wordDoc.Tables.Item(1).Cell(7, 1).Range.Text = "工龄:"; wordDoc.Tables.Item(1).Cell(7, 2).Range.Text = Convert.ToString(MyDS_Grid.Tables[0].Rows[i][11]); wordDoc.Tables.Item(1).Cell(7, 3).Range.Text = "职工类别:"; wordDoc.Tables.Item(1).Cell(7, 4).Range.Text = MyDS_Grid.Tables[0].Rows[i][12].ToString(); wordDoc.Tables.Item(1).Cell(7, 5).Range.Text = "职务类别:"; wordDoc.Tables.Item(1).Cell(7, 6).Range.Text = MyDS_Grid.Tables[0].Rows[i][13].ToString(); //第8行赋值 wordDoc.Tables.Item(1).Cell(8, 1).Range.Text = "工资类别:"; wordDoc.Tables.Item(1).Cell(8, 2).Range.Text = MyDS_Grid.Tables[0].Rows[i][14].ToString(); wordDoc.Tables.Item(1).Cell(8, 3).Range.Text = "部门类别:"; wordDoc.Tables.Item(1).Cell(8, 4).Range.Text = MyDS_Grid.Tables[0].Rows[i][15].ToString(); wordDoc.Tables.Item(1).Cell(8, 5).Range.Text = "职称类别:"; wordDoc.Tables.Item(1).Cell(8, 6).Range.Text = MyDS_Grid.Tables[0].Rows[i][16].ToString(); //第9行赋值 wordDoc.Tables.Item(1).Cell(9, 1).Range.Text = "月工资:"; wordDoc.Tables.Item(1).Cell(9, 2).Range.Text = Convert.ToString(MyDS_Grid.Tables[0].Rows[i][26]); wordDoc.Tables.Item(1).Cell(9, 3).Range.Text = "银行帐号:"; wordDoc.Tables.Item(1).Cell(9, 4).Range.Text = MyDS_Grid.Tables[0].Rows[i][27].ToString(); //第10行赋值 wordDoc.Tables.Item(1).Cell(10, 1).Range.Text = "合同起始日期:"; try { wordDoc.Tables.Item(1).Cell(10, 2).Range.Text = Convert.ToString(Convert.ToDateTime(MyDS_Grid.Tables[0].Rows[i][28]).ToShortDateString()); } catch { wordDoc.Tables.Item(1).Cell(10, 2).Range.Text = ""; } //Convert.ToString(MyDS_Grid.Tables[0].Rows[i][28]); wordDoc.Tables.Item(1).Cell(10, 3).Range.Text = "合同结束日期:"; try { wordDoc.Tables.Item(1).Cell(10, 4).Range.Text = Convert.ToString(Convert.ToDateTime(MyDS_Grid.Tables[0].Rows[i][29]).ToShortDateString()); } catch { wordDoc.Tables.Item(1).Cell(10, 4).Range.Text = ""; } //Convert.ToString(MyDS_Grid.Tables[0].Rows[i][29]); wordDoc.Tables.Item(1).Cell(10, 5).Range.Text = "合同年限:"; wordDoc.Tables.Item(1).Cell(10, 6).Range.Text = Convert.ToString(MyDS_Grid.Tables[0].Rows[i][30]); //第11行赋值 wordDoc.Tables.Item(1).Cell(11, 1).Range.Text = "电话:"; wordDoc.Tables.Item(1).Cell(11, 2).Range.Text = MyDS_Grid.Tables[0].Rows[i][17].ToString(); wordDoc.Tables.Item(1).Cell(11, 3).Range.Text = "手机:"; wordDoc.Tables.Item(1).Cell(11, 4).Range.Text = MyDS_Grid.Tables[0].Rows[i][18].ToString(); wordDoc.Tables.Item(1).Cell(11, 5).Range.Text = "毕业时间:"; try { wordDoc.Tables.Item(1).Cell(11, 6).Range.Text = Convert.ToString(Convert.ToDateTime(MyDS_Grid.Tables[0].Rows[i][21]).ToShortDateString()); } catch { wordDoc.Tables.Item(1).Cell(11, 6).Range.Text = ""; } //Convert.ToString(MyDS_Grid.Tables[0].Rows[i][21]); //第12行赋值 wordDoc.Tables.Item(1).Cell(12, 1).Range.Text = "毕业学校:"; wordDoc.Tables.Item(1).Cell(12, 2).Range.Text = MyDS_Grid.Tables[0].Rows[i][19].ToString(); //第13行赋值 wordDoc.Tables.Item(1).Cell(13, 1).Range.Text = "主修专业:"; wordDoc.Tables.Item(1).Cell(13, 2).Range.Text = MyDS_Grid.Tables[0].Rows[i][20].ToString(); //第14行赋值 wordDoc.Tables.Item(1).Cell(14, 1).Range.Text = "家庭地址:"; wordDoc.Tables.Item(1).Cell(14, 2).Range.Text = MyDS_Grid.Tables[0].Rows[i][22].ToString(); wordDoc.Range(ref start, ref end).InsertParagraphAfter(); //插入回车 wordDoc.Range(ref start, ref end).ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; //设置字体局中 } }
public void CreateTalbe(DataSet ObjData, string strBookMarkName) { if (ObjData.Tables[0].Rows.Count != 0) { object missing = System.Reflection.Missing.Value; //object start = 0; //object end = 0; //Word.Range tableLocation = oWordApplic.ActiveDocument.Range(ref start, ref end); Word.Range tableLocation = GotoBookMark(strBookMarkName); int rowCount; int colCount; ////判断是否包含选择列 //bool hasSelectColumn; //hasSelectColumn = false; //foreach (TableCell tc in HeadRow.Cells) //{ // if (tc.Text == " ") // { // hasSelectColumn = true; // break; // } //} //if (hasSelectColumn) //{ // colCount = HeadRow.Cells.Count - 1; //} //else //{ // colCount = HeadRow.Cells.Count; //} //在WORD中生成表格,列数为表的列数,行数为表的行数加1,因为有列标题行 ObjData.Tables[0].Columns.Remove("project_code"); ObjData.Tables[0].Columns.Remove("contract_name"); ObjData.Tables[0].Columns.Remove("num"); DataTable dt = ObjData.Tables[0]; colCount = dt.Columns.Count; rowCount = dt.Rows.Count + 1; Word.Table objTable = oWordApplic.Selection.Tables.Add(tableLocation, rowCount, colCount, ref missing, ref missing); Word.Border border = objTable.Borders[Word.WdBorderType.wdBorderLeft]; border.LineStyle = Word.WdLineStyle.wdLineStyleSingle; border.LineWidth = Word.WdLineWidth.wdLineWidth050pt; border.Color = Word.WdColor.wdColorAutomatic; border = objTable.Borders[Word.WdBorderType.wdBorderRight]; border.LineStyle = Word.WdLineStyle.wdLineStyleSingle; border.LineWidth = Word.WdLineWidth.wdLineWidth050pt; border.Color = Word.WdColor.wdColorAutomatic; border = objTable.Borders[Word.WdBorderType.wdBorderTop]; border.LineStyle = Word.WdLineStyle.wdLineStyleSingle; border.LineWidth = Word.WdLineWidth.wdLineWidth050pt; border.Color = Word.WdColor.wdColorAutomatic; border = objTable.Borders[Word.WdBorderType.wdBorderBottom]; border.LineStyle = Word.WdLineStyle.wdLineStyleSingle; border.LineWidth = Word.WdLineWidth.wdLineWidth050pt; border.Color = Word.WdColor.wdColorAutomatic; border = objTable.Borders[Word.WdBorderType.wdBorderHorizontal]; border.LineStyle = Word.WdLineStyle.wdLineStyleSingle; border.LineWidth = Word.WdLineWidth.wdLineWidth050pt; border.Color = Word.WdColor.wdColorAutomatic; border = objTable.Borders[Word.WdBorderType.wdBorderVertical]; border.LineStyle = Word.WdLineStyle.wdLineStyleSingle; border.LineWidth = Word.WdLineWidth.wdLineWidth050pt; border.Color = Word.WdColor.wdColorAutomatic; int colIndex; int rowIndex; //创建列标题行 colIndex = 0; if (ObjData.Tables[0].TableName == "project_contract_estate_element") { foreach (DataColumn dc in dt.Columns) { colIndex += 1; if (dc.ColumnName == "obligee") { objTable.Cell(1, colIndex).Range.InsertAfter("房地产权利人"); } else if (dc.ColumnName == "credentials") { objTable.Cell(1, colIndex).Range.InsertAfter("房地产证号"); } else if (dc.ColumnName == "detail") { objTable.Cell(1, colIndex).Range.InsertAfter("房地产名称、栋号、房号"); } } } else if (ObjData.Tables[0].TableName == "project_contract_chattel_element") { foreach (DataColumn dc in dt.Columns) { colIndex += 1; objTable.Cell(1, colIndex).Range.Select(); this.SetAlignment("Center"); if (dc.ColumnName == "name") { objTable.Cell(1, colIndex).Range.InsertAfter("名称"); objTable.Columns[colIndex].PreferredWidthType = Word.WdPreferredWidthType.wdPreferredWidthPercent; objTable.Columns[colIndex].PreferredWidth = 25F; } else if (dc.ColumnName == "amount") { objTable.Cell(1, colIndex).Range.InsertAfter("数量"); objTable.Columns[colIndex].PreferredWidthType = Word.WdPreferredWidthType.wdPreferredWidthPercent; objTable.Columns[colIndex].PreferredWidth = 10F; } else if (dc.ColumnName == "source_amount") { objTable.Cell(1, colIndex).Range.InsertAfter("原值"); objTable.Columns[colIndex].PreferredWidthType = Word.WdPreferredWidthType.wdPreferredWidthPercent; objTable.Columns[colIndex].PreferredWidth = 15F; } else if (dc.ColumnName == "specification") { objTable.Cell(1, colIndex).Range.InsertAfter("编号(型号)"); objTable.Columns[colIndex].PreferredWidthType = Word.WdPreferredWidthType.wdPreferredWidthPercent; objTable.Columns[colIndex].PreferredWidth = 25F; } else if (dc.ColumnName == "invoice_num") { objTable.Cell(1, colIndex).Range.InsertAfter("发票号码"); objTable.Columns[colIndex].PreferredWidthType = Word.WdPreferredWidthType.wdPreferredWidthPercent; objTable.Columns[colIndex].PreferredWidth = 25F; } } } else if (ObjData.Tables[0].TableName == "project_contract_car_element") { foreach (DataColumn dc in dt.Columns) { colIndex += 1; objTable.Cell(1, colIndex).Range.Select(); this.SetAlignment("Center"); if (dc.ColumnName == "car_owner") { objTable.Cell(1, colIndex).Range.InsertAfter("机动车所有人"); } else if (dc.ColumnName == "car_type") { objTable.Cell(1, colIndex).Range.InsertAfter("车辆类型"); } else if (dc.ColumnName == "car_register_num") { objTable.Cell(1, colIndex).Range.InsertAfter("机动车登记编号"); } else if (dc.ColumnName == "car_num") { objTable.Cell(1, colIndex).Range.InsertAfter("车牌号码"); } else if (dc.ColumnName == "car_brand_num") { objTable.Cell(1, colIndex).Range.InsertAfter("品牌型号"); } } } //创建数据行 rowIndex = 1; foreach (DataRow dr in dt.Rows) { rowIndex += 1; colIndex = 0; foreach (DataColumn dc in dr.Table.Columns) { colIndex += 1; objTable.Cell(rowIndex, colIndex).Range.InsertAfter(dr[dc.ColumnName].ToString()); objTable.Cell(rowIndex, colIndex).Range.Select(); this.SetAlignment("Center"); } } //设置表格格式 //objTable.Borders.InsideLineStyle = 1; //objTable.Borders.OutsideLineStyle = 1; } //// this function doesn't work //public void InsertPageNumber( string strType, bool bHeader ) //{ // object missing = System.Reflection.Missing.Value; // object alignment ; // object bFirstPage = false; // object bF = true; // //if (bHeader == true) // //WordApplic.Selection.HeaderFooter.PageNumbers.ShowFirstPageNumber = bF; // switch (strType) // { // case "Center": // alignment = Word.WdPageNumberAlignment.wdAlignPageNumberCenter; // //WordApplic.Selection.HeaderFooter.PageNumbers.Add(ref alignment,ref bFirstPage); // //Word.Selection objSelection = WordApplic.pSelection; // oWordApplic.Selection.HeaderFooter.PageNumbers.Item(1).Alignment = Word.WdPageNumberAlignment.wdAlignPageNumberCenter; // break; // case "Right": // alignment = Word.WdPageNumberAlignment.wdAlignPageNumberRight; // oWordApplic.Selection.HeaderFooter.PageNumbers.Item(1).Alignment = Word.WdPageNumberAlignment.wdAlignPageNumberRight; // break; // case "Left": // alignment = Word.WdPageNumberAlignment.wdAlignPageNumberLeft; // oWordApplic.Selection.HeaderFooter.PageNumbers.Add(ref alignment,ref bFirstPage); // break; // } //} }
/// <summary> /// 动态创建table到word /// </summary> protected void CreateTableToExcel() { Word.Application app = null; Word.Document doc = null; try { //构造数据 List <Student> datas = new List <Student>(); datas.Add(new Student { Leader = "小李", Name = "张三", Score = 498, StuClass = "一班" }); datas.Add(new Student { Leader = "陈飞", Name = "李四", Score = 354, StuClass = "二班" }); datas.Add(new Student { Leader = "陈飞", Name = "小红", Score = 502, StuClass = "二班" }); datas.Add(new Student { Leader = "王林", Name = "丁爽", Score = 566, StuClass = "三班" }); var cate = datas.GroupBy(s => s.StuClass); int rows = cate.Count() + 1; //表格行数加1是为了标题栏 int cols = 5; //表格列数 object oMissing = System.Reflection.Missing.Value; app = new Word.Application(); //创建word应用程序 doc = app.Documents.Add(); //添加一个word文档 //输出大标题加粗加大字号水平居中 app.Selection.Font.Bold = 700; app.Selection.Font.Size = 16; app.Selection.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; app.Selection.Text = "班级成绩统计单"; //换行添加表格 object line = Word.WdUnits.wdLine; app.Selection.MoveDown(ref line, oMissing, oMissing); app.Selection.TypeParagraph();//换行 Word.Range range = app.Selection.Range; Word.Table table = app.Selection.Tables.Add(range, rows, cols, ref oMissing, ref oMissing); //设置表格的字体大小粗细 table.Range.Font.Size = 10; table.Range.Font.Bold = 0; //设置表格标题 int rowIndex = 1; table.Cell(rowIndex, 1).Range.Text = "班级"; table.Cell(rowIndex, 2).Range.Text = "姓名"; table.Cell(rowIndex, 3).Range.Text = "成绩"; table.Cell(rowIndex, 4).Range.Text = "人数"; table.Cell(rowIndex, 5).Range.Text = "班主任"; //循环数据创建数据行 rowIndex++; foreach (var i in cate) { table.Cell(rowIndex, 1).Range.Text = i.Key; //班级 table.Cell(rowIndex, 4).Range.Text = i.Count().ToString(); //人数 table.Cell(rowIndex, 5).Range.Text = i.First().Leader; //班主任 table.Cell(rowIndex, 2).Split(i.Count(), 1); //分割名字单元格 table.Cell(rowIndex, 3).Split(i.Count(), 1); //分割成绩单元格 //对表格中的班级、姓名,成绩单元格设置上下居中 table.Cell(rowIndex, 1).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; table.Cell(rowIndex, 4).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; table.Cell(rowIndex, 5).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; //构建姓名,成绩数据 foreach (var x in i) { table.Cell(rowIndex, 2).Range.Text = x.Name; table.Cell(rowIndex, 3).Range.Text = x.Score.ToString(); rowIndex++; } } //导出到文件 string newFile = DateTime.Now.ToString("yyyyMMddHHmmssss") + ".doc"; string physicNewFile = Server.MapPath(newFile); doc.SaveAs(physicNewFile, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing); } catch (Exception ex) { } finally { if (doc != null) { doc.Close();//关闭文档 } if (app != null) { app.Quit();//退出应用程序 } } }
private string GetDocumentText(object path, int tryCount) { if (tryCount++ > 1) { return(string.Empty); } Word.Documents documents = null; try { if (_MSWord == null) { if (!LoadWordInstance()) { return(string.Empty); } } documents = _MSWord.Documents; } catch (InvalidCastException exception) { _tracer.TraceException(exception); return(GetDocumentTextWithReloadingWord(path, tryCount)); } catch (System.Runtime.InteropServices.COMException exception) { _tracer.TraceException(exception); if (IsReloadingPossible(exception)) { return(GetDocumentTextWithReloadingWord(path, tryCount)); } return(string.Empty); } catch (Exception exception) { _tracer.TraceException(exception); return(string.Empty); } Word.Document doc = null; string bodyText = string.Empty; object pass = "******"; try { DisableAutomationSecurity(); doc = documents.Open(ref path, ref FALSE, ref TRUE, ref FALSE, ref pass, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue); Word.Range range = doc.Content; bodyText = range.Text; } catch (System.Runtime.InteropServices.COMException exception) { _tracer.TraceException(exception); if (IsReloadingPossible(exception)) { _tracer.Trace("Try to load new instance of MS Word"); return(GetDocumentTextWithReloadingWord(path, tryCount)); } if (COM_Error.CouldNotOpenMacroStorage(exception)) //This exception leads to not closed documents { LoadWordInstance(); return(string.Empty); } } catch (InvalidCastException exception) { _tracer.TraceException(exception); return(GetDocumentTextWithReloadingWord(path, tryCount)); } catch (Exception exception) { _tracer.TraceException(exception); return(string.Empty); } RestoreAutomationSecurity(); try { if (doc != null) { doc.Close(ref FALSE, ref MissingValue, ref MissingValue); } return(bodyText); } catch (System.Runtime.InteropServices.COMException exception) { if (IsReloadingPossible(exception)) { return(GetDocumentTextWithReloadingWord(path, tryCount)); } } catch (InvalidCastException exception) { _tracer.TraceException(exception); return(GetDocumentTextWithReloadingWord(path, tryCount)); } catch (Exception exception) { _tracer.TraceException(exception); } return(string.Empty); }
/// <summary> /// Determines the pagenumber of a range. /// </summary> /// <param name="range">The range to be located.</param> /// <returns></returns> private static int GetPageNumberOfRange(Word.Range range) { return((int)range.get_Information(Word.WdInformation.wdActiveEndPageNumber)); }
public void Export_Data_To_Word(DataGridView DGV, string filename) { if (DGV.Rows.Count != 0) { int RowCount = DGV.Rows.Count; int ColumnCount = DGV.Columns.Count; Object[,] DataArray = new object[RowCount + 1, ColumnCount + 1]; //add rows int r = 0; for (r = 0; r <= RowCount - 1; r++) { for (int c = 0; c <= ColumnCount - 1; c++) { DataArray[r, c] = DGV.Rows[r].Cells[c].Value; } //end row loop } //end column loop Word.Document oDoc = new Word.Document(); oDoc.Application.Visible = true; //page orintation oDoc.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape; dynamic oRange = oDoc.Content.Application.Selection.Range; string oTemp = ""; Object oMissing = System.Reflection.Missing.Value; for (r = 0; r <= RowCount - 1; r++) { for (int c = 0; c <= ColumnCount - 1; c++) { oTemp = oTemp + DataArray[r, c] + "\t"; } } //table format oRange.Text = oTemp; object Separator = Word.WdTableFieldSeparator.wdSeparateByTabs; object ApplyBorders = true; object AutoFit = true; object AutoFitBehavior = Word.WdAutoFitBehavior.wdAutoFitContent; oRange.ConvertToTable(ref Separator, ref RowCount, ref ColumnCount, Type.Missing, Type.Missing, ref ApplyBorders, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, ref AutoFit, ref AutoFitBehavior, Type.Missing); oRange.Select(); oDoc.Application.Selection.Tables[1].Select(); oDoc.Application.Selection.Tables[1].Rows.AllowBreakAcrossPages = 0; oDoc.Application.Selection.Tables[1].Rows.Alignment = 0; oDoc.Application.Selection.Tables[1].Rows[1].Select(); oDoc.Application.Selection.InsertRowsAbove(1); oDoc.Application.Selection.Tables[1].Rows[1].Select(); //header row style oDoc.Application.Selection.Tables[1].Rows[1].Range.Bold = 1; oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Name = "Tahoma"; oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Size = 14; //add header row manually for (int c = 0; c <= ColumnCount - 1; c++) { oDoc.Application.Selection.Tables[1].Cell(1, c + 1).Range.Text = DGV.Columns[c].HeaderText; } //table style oDoc.Application.Selection.Tables[1].set_Style("Grid Table 4 - Accent 5"); oDoc.Application.Selection.Tables[1].Rows[1].Select(); oDoc.Application.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; //header text foreach (Word.Section section in oDoc.Application.ActiveDocument.Sections) { Word.Range headerRange = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range; headerRange.Fields.Add(headerRange, Word.WdFieldType.wdFieldPage); headerRange.Text = "Course list table"; headerRange.Font.Size = 16; headerRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; } //save the file oDoc.SaveAs(filename); } }
private void CheckSpelling() { TextDocumentHandler handler = new TextDocumentHandler(this.dte); if (handler.HasNonEmptySelection) { try { // Launch Word. Word._Application wordApp = new Word.Application(); // Add a document. Word._Document wordDoc = wordApp.Documents.Add(); // Clear current contents. Word.Range range = wordApp.Selection.Range; range.WholeStory(); range.Delete(); range = null; // Add the text the user selected. wordApp.Selection.Text = handler.SelectedText; // Show it wordApp.Visible = true; wordApp.Activate(); wordDoc.Activate(); // Check spelling wordDoc.CheckSpelling(); // Get the edited text back wordApp.Selection.WholeStory(); string newText = wordApp.Selection.Text; // Word always adds an extra CR, so strip that off. // Also it converts all LFs to CRs, so change // that back. if (!string.IsNullOrEmpty(newText)) { if (newText.EndsWith("\r")) { newText = newText.Substring(0, newText.Length - 1); } newText = newText.Replace("\r", "\r\n"); } handler.SetSelectedTextIfUnchanged(newText, "Check Spelling"); // Tell the doc and Word to go away. object saveChanges = false; wordDoc.Close(ref saveChanges); wordApp.Visible = false; wordApp.Quit(); } catch (COMException ex) { // If we get REGDB_E_CLASSNOTREG, then Word probably isn't installed. const uint REGDB_E_CLASSNOTREG = 0x80040154; if (unchecked ((uint)ex.ErrorCode) == REGDB_E_CLASSNOTREG) { this.package.ShowMessageBox( "Microsoft Word is required in order to check spelling, but it isn't available.\r\n\r\nDetails:\r\n" + ex.Message, true); } else { throw; } } } }