private void ProcessHeaderFooter(Microsoft.Office.Interop.Word.Application wApp, Microsoft.Office.Interop.Word.Document wDoc) { // copy header wApp.ActiveWindow.ActivePane.View.Type = Microsoft.Office.Interop.Word.WdViewType.wdPrintView; wApp.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageHeader; Microsoft.Office.Interop.Word.Range wHeaderRange = wApp.Selection.HeaderFooter.Range; ProcessBookmarks(wHeaderRange.Bookmarks, wDoc); wHeaderRange.CopyAsPicture(); // paste header wApp.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument; wApp.Selection.HomeKey(Microsoft.Office.Interop.Word.WdUnits.wdStory); Microsoft.Office.Interop.Word.Paragraph wHeader = wDoc.Content.Paragraphs.Add(); wApp.Selection.PasteAndFormat(Microsoft.Office.Interop.Word.WdRecoveryType.wdPasteDefault); // copy footer wApp.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageFooter; Microsoft.Office.Interop.Word.Range wFooterRange = wApp.Selection.HeaderFooter.Range; ProcessBookmarks(wFooterRange.Bookmarks, wDoc); wFooterRange.CopyAsPicture(); // paste footer wApp.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument; wApp.Selection.EndKey(Microsoft.Office.Interop.Word.WdUnits.wdStory); Microsoft.Office.Interop.Word.Paragraph wFooter = wDoc.Content.Paragraphs.Add(); wApp.Selection.PasteAndFormat(Microsoft.Office.Interop.Word.WdRecoveryType.wdPasteDefault); }
private void procfile(FileInfo fi) { try { Word.Document wordDoc = app.Documents.Open(fi.FullName); Microsoft.Office.Interop.Word.Range docRanger = wordDoc.Content; //页数 int Pages = docRanger.ComputeStatistics(Word.WdStatistic.wdStatisticPages); //字数 int Words = docRanger.ComputeStatistics(Word.WdStatistic.wdStatisticWords); //字符数(不计空格) int Characters = docRanger.ComputeStatistics(Word.WdStatistic.wdStatisticCharacters); //字符数(计空格) int Characterswithspaces = docRanger.ComputeStatistics(Word.WdStatistic.wdStatisticCharactersWithSpaces); //段落数 int Paragraphs = docRanger.ComputeStatistics(Word.WdStatistic.wdStatisticParagraphs); //行数 int Lines = docRanger.ComputeStatistics(Word.WdStatistic.wdStatisticLines); //MessageBox.Show(fi.Name+":"+ Words.ToString()); WordList.Add(new WordInfo { fileName = fi.Name, filePath = fi.DirectoryName, wordCount = Words, createTime = fi.CreationTime.ToString(), lastTime = fi.LastAccessTime.ToString() }); wordDoc.Close(); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
private void wordToolStripMenuItem_Click(object sender, EventArgs e) { saveFileDialog2.Filter = "doc files (*.doc)|*.doc|All files (*.*)|*.*"; saveFileDialog2.FilterIndex = 2; saveFileDialog2.RestoreDirectory = true; if (saveFileDialog2.ShowDialog() == DialogResult.OK) { Microsoft.Office.Interop.Word.Application application = new Microsoft.Office.Interop.Word.Application(); Object missing = Type.Missing; Word.Document word1 = application.Documents.Add(ref missing, ref missing, ref missing, ref missing); //object text = "tesfsdfkslghsdgjh"; //word1.Paragraphs[1].Range.InsertParagraphAfter(); //word1.Paragraphs[1].Range.Text = "asaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; //word1.Footnotes.Location = Word.WdFootnoteLocation.wdBeneathText; //word1.Footnotes.NumberStyle = Word.WdNoteNumberStyle.wdNoteNumberStyleLowercaseRoman; //word1.Footnotes.Add(word1.Paragraphs[1].Range.Words[2].Characters[2], ref missing, ref text); Microsoft.Office.Interop.Word.Document doc = application.ActiveDocument; Microsoft.Office.Interop.Word.Range range = doc.Paragraphs[doc.Paragraphs.Count].Range; dataSetTemp = dbw1.ReadMetricsByReport(listView2.Items[listView2.SelectedIndices[0]].Text); doc.Tables.Add(range, dataSetTemp.Tables[0].Rows.Count + 1, 6, ref missing, ref missing); doc.Tables[1].Cell(1, 1).Range.Text = "NAME metric"; doc.Tables[1].Cell(1, 2).Range.Text = "MIN value"; doc.Tables[1].Cell(1, 3).Range.Text = "CUR value"; doc.Tables[1].Cell(1, 4).Range.Text = "MAX value"; doc.Tables[1].Cell(1, 5).Range.Text = "VALUE"; doc.Tables[1].Cell(1, 6).Range.Text = "RATE"; for (int i = 0; i < dataSetTemp.Tables[0].Rows.Count; i++) { dataSetTemp1 = dbw1.ReadInfoMetricByReportMetric(listView2.Items[listView2.SelectedIndices[0]].Text, dataSetTemp.Tables[0].Rows[i].ItemArray[0].ToString()); doc.Tables[1].Cell(i + 2, 1).Range.Text = dataSetTemp.Tables[0].Rows[i].ItemArray[0].ToString(); doc.Tables[1].Cell(i + 2, 2).Range.Text = dataSetTemp1.Tables[0].Rows[0].ItemArray[2].ToString(); doc.Tables[1].Cell(i + 2, 3).Range.Text = dataSetTemp1.Tables[0].Rows[0].ItemArray[0].ToString(); doc.Tables[1].Cell(i + 2, 4).Range.Text = dataSetTemp1.Tables[0].Rows[0].ItemArray[3].ToString(); doc.Tables[1].Cell(i + 2, 5).Range.Text = Double.Parse(dataSetTemp1.Tables[0].Rows[0].ItemArray[4].ToString()).ToString("F5"); doc.Tables[1].Cell(i + 2, 6).Range.Text = dataSetTemp1.Tables[0].Rows[0].ItemArray[5].ToString(); } doc.Tables[1].Columns.AutoFit(); Word.Border[] borders = new Word.Border[6]; Word.Table tbl = doc.Tables[doc.Tables.Count]; borders[0] = tbl.Borders[Word.WdBorderType.wdBorderLeft]; borders[1] = tbl.Borders[Word.WdBorderType.wdBorderRight]; borders[2] = tbl.Borders[Word.WdBorderType.wdBorderTop]; borders[3] = tbl.Borders[Word.WdBorderType.wdBorderBottom]; borders[4] = tbl.Borders[Word.WdBorderType.wdBorderHorizontal]; borders[5] = tbl.Borders[Word.WdBorderType.wdBorderVertical]; foreach (Word.Border border in borders) { border.LineStyle = Word.WdLineStyle.wdLineStyleSingle; border.Color = Word.WdColor.wdColorBlack; } application.Documents[word1].SaveAs(saveFileDialog2.FileName, 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); application.Quit(); string info = "Doc file saved at\n" + saveFileDialog2.FileName; MessageBox.Show(this, info, "Info", MessageBoxButtons.OK, MessageBoxIcon.Information); } }
/// <summary> /// Thêm dữ liệu ở cuối nội dung của word. /// </summary> /// <param name="values">Dữ liệu thêm</param> public void InsertRowsAfter(string values) { try { Microsoft.Office.Interop.Word.Range objWordRng = doc.Bookmarks.get_Item(ref objEndOfDocFlag).Range; //go to end of document objWordRng.InsertParagraphAfter(); //put enter in document objWordRng.InsertAfter(values); } catch { } }
/// <summary> /// Thay thế nội dung của bảng dữ liệu trong word. /// </summary> /// <param name="fieldName">Biến cần thay đổi</param> /// <param name="values">Nội dung cần thay đổi</param> public void WriteDataFields(string fieldName, string values) { try { Microsoft.Office.Interop.Word.Range rng = doc.Content; for (int i = 0; i < rng.Paragraphs.Count; i++) { if (rng.Paragraphs[i + 1].Range.Text.IndexOf(fieldName) != -1) { rng.Paragraphs[i + 1].Range.Text = rng.Paragraphs[i + 1].Range.Text.Replace(fieldName, values); } } } catch { } }
private static void ReplaceBookmarkText(Microsoft.Office.Interop.Word.Document doc, string bookmarkName, string text) { if (doc.Bookmarks.Exists(bookmarkName)) { Object name = bookmarkName; Microsoft.Office.Interop.Word.Range range = doc.Bookmarks.get_Item(ref name).Range; range.Text = text; object newRange = range; doc.Bookmarks.Add(bookmarkName, ref newRange); } }
private void AddMergeField(string stFieldName) { try { SplashScreenManager.ShowForm(null, typeof(WaitForm1), true, true, false); SplashScreenManager.Default.SetWaitFormDescription("Bitte warten…"); Object objType = Word.WdFieldType.wdFieldMergeField; Object oMissing = System.Reflection.Missing.Value; Object objFieldName = stFieldName; Word.Application WordApp = new Word.Application(); Word.Document WordDoc = Globals.ThisAddIn.Application.ActiveDocument; dynamic oRange = WordDoc.Content.Application.Selection.Range; Microsoft.Office.Interop.Word.Range rngFieldCode = oRange; Word.Field field = rngFieldCode.Fields.Add(rngFieldCode, ref objType, ref objFieldName, ref oMissing); } catch (Exception ex) {} finally { SplashScreenManager.CloseForm(false); } }
public void addLink(int index, string file_name) { try { Microsoft.Office.Interop.Word.Selection linkSelection = word_app.ActiveWindow.Selection; linkSelection.Start = 9999; linkSelection.End = 9999; Microsoft.Office.Interop.Word.Range linkRange = linkSelection.Range; Microsoft.Office.Interop.Word.Hyperlinks bookmarksLinks = word_wrt.Hyperlinks; string file_Path = this.created_folder + "\\" + file_name; object linkAddr = file_Path; string single_bookmark = bookmark_list[index]; object linkSubAddr = single_bookmark; // you may need more parameters here Microsoft.Office.Interop.Word.Hyperlink bookmarkLink = bookmarksLinks.Add(linkRange, ref linkAddr, ref linkSubAddr); bookmarkLink.Range.Font.Size = 8; word_app.ActiveWindow.Selection.InsertAfter("\n"); //落款 word_wrt.Paragraphs.Last.Range.Text = "created in:" + DateTime.Now.ToString(); //myWordDoc.Paragraphs.Last.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight; //保存 //myWordDoc.Save(); //myWordDoc.Close(ref oMissing, ref oMissing, ref oMissing); //myWordApp.Quit(ref oMissing, ref oMissing, ref oMissing); //return true; } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); //return false; } }
public bool InsertTable(DataTable dt, bool haveBorder, double[] colWidths, string[] MergeAry) { try { object Nothing = System.Reflection.Missing.Value; int lenght = oDoc.Characters.Count - 1; object start = lenght; object end = lenght; //表格起始坐标 Microsoft.Office.Interop.Word.Range tableLocation = oDoc.Range(ref start, ref end); //添加Word表格 Microsoft.Office.Interop.Word.Table table = oDoc.Tables.Add(tableLocation, dt.Rows.Count, dt.Columns.Count, ref Nothing, ref Nothing); if (colWidths != null) { for (int i = 0; i < colWidths.Length; i++) { table.Columns[i + 1].Width = (float)(28.5F * colWidths[i]); } } ///设置TABLE的样式 table.Rows.HeightRule = Microsoft.Office.Interop.Word.WdRowHeightRule.wdRowHeightAtLeast; table.Rows.Height = oWordApplic.CentimetersToPoints(float.Parse("0.8")); table.Range.Font.Size = 10.5F; table.Range.Font.Name = "宋体"; table.Range.Font.Bold = 0; table.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; table.Range.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; if (haveBorder == true) { //设置外框样式 table.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle; table.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle; //样式设置结束 } for (int row = 0; row < dt.Rows.Count; row++) { for (int col = 0; col < dt.Columns.Count; col++) { table.Cell(row + 1, col + 1).Range.Text = dt.Rows[row][col].ToString(); } } if (MergeAry != null) { foreach (string mStr in MergeAry) { string[] cellStr = mStr.Split(','); table.Cell(int.Parse(cellStr[0]), int.Parse(cellStr[1])) .Merge(table.Cell(int.Parse(cellStr[2]), int.Parse(cellStr[3]))); } } ////table.Cell(dt.Rows.Count,2).Merge(table.Cell(dt.Rows.Count,dt.Columns.Count)); ////table.Cell(dt.Rows.Count, 1).Merge(table.Cell(dt.Rows.Count, 3)); return(true); } catch (Exception e) { //MessageBox.Show(e.ToString(), "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } finally { } }
/*Avendo già memmorizzato i dati ( Cliente1.Nome = txtNome.Text; e Cliente1.Cognome = txtCognome.Text;)*/ public static void scrittura(bool intestazione, Cliente cliente) { object missing = System.Reflection.Missing.Value; Word.Application wordApp = new Word.Application(); wordApp.Visible = false; wordApp.WindowState = Word.WdWindowState.wdWindowStateNormal; Word.Document wordDoc = wordApp.Documents.Add(); var path = @"" + Path.GetFullPath("image.jpg"); Word.Range range; //se la CheckBox dell'intestazione è checkata if (intestazione) { //incollo l'immagine come intestazione foreach (Microsoft.Office.Interop.Word.Section section in wordDoc.Sections) { //Get the header range and add the header details. Microsoft.Office.Interop.Word.Range docRange = section.Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range; docRange.Fields.Add(docRange, Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage); // Create an InlineShape in the InlineShapes collection where the picture should be added later // It is used to get automatically scaled sizes. Word.InlineShape autoScaledInlineShape = docRange.InlineShapes.AddPicture(path); float scaledWidth = autoScaledInlineShape.Width; float scaledHeight = autoScaledInlineShape.Height; autoScaledInlineShape.Delete(); // Create a new Shape and fill it with the picture Word.Shape newShape = wordDoc.Shapes.AddShape(1, 0, 0, scaledWidth, scaledHeight); newShape.Fill.UserPicture(path); // Convert the Shape to an InlineShape and optional disable Border Word.InlineShape finalInlineShape = newShape.ConvertToInlineShape(); finalInlineShape.Line.Visible = Microsoft.Office.Core.MsoTriState.msoFalse; // Cut the range of the InlineShape to clipboard finalInlineShape.Range.Cut(); // And paste it to the target Range docRange.Paste(); } } //formattazione testo (se la modifichi occhio alle tabulazioni sotto) wordDoc.Content.SetRange(0, 0); wordDoc.Content.Font.Size = 15; // Get the current date DateTime thisDay = DateTime.Today; // intestazione con nome cognome e data: wordDoc.Content.Text = "Preventivo\t\t\t\t\t\t\t\t\t\t" + thisDay.ToString("d") + "\nRiferimento: " + cliente.Nome + " " + cliente.Cognome + "\n" + Environment.NewLine; int i = 0; ArrayList totali_singoli_prodotti = new ArrayList(); //creo un array formato dal totale dei prodotti per riempire una tab alla fine //per ogni prodotto presente nell'array: foreach (Prodotto prodotto in cliente.ListaProdotti) { if (!string.IsNullOrWhiteSpace(cliente.ListaProdotti[i].NomeProdotto)) { range = GetRange(wordDoc); //stampo la tabella con le caratteristiche del singolo prodotto Word.Table tab = wordDoc.Tables.Add(range, 9, 3, ref missing, ref missing); tab.Borders.Enable = 1; // tabella prodotto n foreach (Word.Row row in tab.Rows) { foreach (Word.Cell cell in row.Cells) { cell.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; cell.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; //la colonna con la descrizione del prodotto la metto con sfondo grigio if (cell.ColumnIndex == 1 || cell.RowIndex == 1) { cell.Shading.BackgroundPatternColor = Word.WdColor.wdColorGray25; } //prima riga if (cell.RowIndex == 1) { if (cell.ColumnIndex == 2) { cell.Range.Text = "Sconto :"; } if (cell.ColumnIndex == 3) { cell.Range.Text = "Totale :"; } } //scrivo le descrizioni nella colonna a sinistra if (cell.ColumnIndex == 1) { if (cell.RowIndex == 2) { if (cliente.ListaProdotti[i].NumeroPezzi != 1) { cell.Range.Text = cliente.ListaProdotti[i].NumeroPezzi + " x " + cliente.ListaProdotti[i].NomeProdotto + ":"; } else { cell.Range.Text = cliente.ListaProdotti[i].NomeProdotto + ":"; } } if (cell.RowIndex == 3) { cell.Range.Text = "Sconto :"; } if (cell.RowIndex == 4) { cell.Range.Text = "Costo :"; } if (cell.RowIndex == 5) { cell.Range.Text = "Ricarica :"; } if (cell.RowIndex == 6) { cell.Range.Text = "Posa :"; } if (cell.RowIndex == 7) { cell.Range.Text = "Trasporti :"; } if (cell.RowIndex == 8) { cell.Range.Text = "Accessori :"; } if (cell.RowIndex == 9) { cell.Range.Text = "Lavorazioni :"; } } //colonna in centro if (cell.ColumnIndex == 2) { if (cell.RowIndex == 3) { cell.Range.Text = cliente.ListaProdotti[i].Sconto + "%"; } if (cell.RowIndex == 5) { cell.Range.Text = cliente.ListaProdotti[i].Ricarica + "%"; } } //colonna destra if (cell.ColumnIndex == 3) { if (cell.RowIndex == 2) { cell.Range.Text = cliente.ListaProdotti[i].PrezzoListino.ToString(); } if (cell.RowIndex == 4) { cell.Range.Text = cliente.ListaProdotti[i].Costo.ToString(); } if (cell.RowIndex == 6) { if (cliente.ListaProdotti[i].UnitaPosa) { cell.Range.Text = cliente.ListaProdotti[i].NumeroPezzi + " x " + cliente.ListaProdotti[i].Posa; } else { cell.Range.Text = cliente.ListaProdotti[i].Posa.ToString(); } } if (cell.RowIndex == 7) { if (cliente.ListaProdotti[i].UnitaTrasporto) { cell.Range.Text = cliente.ListaProdotti[i].NumeroPezzi + " x " + cliente.ListaProdotti[i].Trasporto; } else { cell.Range.Text = cliente.ListaProdotti[i].Trasporto.ToString(); } } if (cell.RowIndex == 8) { if (cliente.ListaProdotti[i].UnitaAccessori) { cell.Range.Text = cliente.ListaProdotti[i].NumeroPezzi + " x " + cliente.ListaProdotti[i].Accessori; } else { cell.Range.Text = cliente.ListaProdotti[i].Accessori.ToString(); } } if (cell.RowIndex == 9) { if (cliente.ListaProdotti[i].UnitaLavorazioni) { cell.Range.Text = cliente.ListaProdotti[i].NumeroPezzi + " x " + cliente.ListaProdotti[i].Lavorazioni; } else { cell.Range.Text = cliente.ListaProdotti[i].Lavorazioni.ToString(); } } } } } range = GetRange(wordDoc); //stampo la tabella con il totale de singolo Prodotto Word.Table TabTotaleProd = wordDoc.Tables.Add(range, 1, 3, ref missing, ref missing); TabTotaleProd.Borders.Enable = 1; foreach (Word.Row row in TabTotaleProd.Rows) { foreach (Word.Cell cell in row.Cells) { //sistemo il background e allineo il testo cell.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; cell.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; //se è nella prima colonna (testo): if (cell.ColumnIndex == 1) { cell.Shading.BackgroundPatternColor = Word.WdColor.wdColorGray25; cell.Range.Text = "Totale Prodotto:"; cell.Range.Font.Bold = 1; } //se è nella terza colonna: else if (cell.ColumnIndex == 3) { cell.Range.Text = cliente.ListaProdotti[i].Totale + ""; } } } //aggiungo il totale di questo prodotto all'array totali_singoli_prodotti.Add(cliente.ListaProdotti[i].Totale); } i++; } i = 0; range = GetRange(wordDoc); //riassunto tutti totali Word.Table tabTotFattura = wordDoc.Tables.Add(range, cliente.ListaProdotti.Count + 2, 2, ref missing, ref missing); tabTotFattura.Borders.Enable = 1; //scorro tutti i prodotti foreach (Prodotto prodotto in cliente.ListaProdotti) { if (!string.IsNullOrWhiteSpace(cliente.ListaProdotti[i].NomeProdotto)) { foreach (Word.Row row in tabTotFattura.Rows) { foreach (Word.Cell cell in row.Cells) { cell.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; cell.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; if (cell.ColumnIndex == 1) { cell.Shading.BackgroundPatternColor = Word.WdColor.wdColorGray25; if (cell.RowIndex == 1) { cell.Range.Text = "Prodotti:"; } if (cell.RowIndex == i + 2) { cell.Range.Text = cliente.ListaProdotti[i].NomeProdotto; } } if (cell.ColumnIndex == 2) { if (cell.RowIndex == 1) { cell.Shading.BackgroundPatternColor = Word.WdColor.wdColorGray25; cell.Range.Text = "Totale:"; } if (cell.RowIndex == i + 2) { cell.Range.Text = cliente.ListaProdotti[i].Totale.ToString(); } if (cell.RowIndex == cliente.ListaProdotti.Count + 2) { cell.Range.Text = cliente.TotaleFattura + " €"; } } } } } i++; } //tabella con il riassunto dei totali: //chiudo var savingPath = @"" + Path.GetFullPath("ArchivioWord") + "\\" + cliente.Nome + cliente.Cognome + cliente.Indice + ".docx"; wordDoc.SaveAs(savingPath); wordDoc.Close(); wordApp.Quit(); }
private void bgWorker1_DoWork(object sender, DoWorkEventArgs e) { try { if (bgWorker1.CancellationPending) { e.Cancel = true; } else { //Lấy thông tin từ class static if (InfoTest.DanhSachNhomCauHoi.Count == 0) { //MessageBox.Show("dto moi them = " + InfoTest.DanhSachNhomCauHoi[0].DuongDan + "; điểm = " + InfoTest.DanhSachNhomCauHoi[0].Diem.ToString()); MessageBox.Show("Không có dữ liệu", "Thông tin", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } // string sKyThi = InfoTest.sKyThi; string sMonThi = InfoTest.sMonThi; string sDoiTuong = InfoTest.sDoiTuong; string sHinhThucThi = InfoTest.sHinhThucThi; string sThoiGian = InfoTest.sThoiGian; string sNgayThangNamThi = InfoTest.sNgayThi + "/" + InfoTest.sThangThi + "/" + InfoTest.sNamThi; int iSoDe = InfoTest.iSoDe;//_soDe là số đề cần tạo ra Được tính từ MaDeTu và MaDeDen // ArrayList dsCauHoiBoDe = new ArrayList(); int iSoCauMax; //n là số câu max trong danh sách câu nhóm 1 int k = 0; int iPhanTramCongViec = 0; //j là số % công việc đang thực hiện //TẠO DANH SACH CÂU HỎI CHO BỘ ĐỀ ĐẢM BẢO YÊU CẦU for (int iNhom = 0; iNhom < InfoTest.DanhSachNhomCauHoi.Count; iNhom++) //Làm từng đề lần lượt { iSoCauMax = InfoTest.DanhSachNhomCauHoi[iNhom].SoCau; List <int> tmp = CreateListTest(iSoCauMax, iSoDe, k); //string ds1 = ""; //foreach (int m in tmp) //{ // ds1 = ds1 + m.ToString() + " "; //} //MessageBox.Show("DS câu nhóm " + iNhom.ToString() +": " + ds1); dsCauHoiBoDe.Add(tmp); k++; } //% mở đề thi mẫu bgWorker1.ReportProgress(5); //Mở MS Word rồi tạo file đề thi để chuẩn bị copy nội dung Word.Application wordApp = new Word.Application(); wordApp.Visible = false; object filename = InfoTest.sThuMucDeMau + "\\DeThiMau3.docx"; List <int> processesbeforegen = getRunningProcesses(); Word.Document docDeThiMau = wordApp.Documents.Open(ref filename, ref missing, ref readOnly, 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);; Word.Document emptyDoc = null; //Tạo tệp tin đề thi emptyDoc = wordApp.Documents.Add(); Word.Document emptyDoc1 = null; //Tạo tệp tin đáp án đề thi emptyDoc1 = wordApp.Documents.Add(); string sTenDe = ""; for (int _iSoDe = 0; _iSoDe < iSoDe; _iSoDe++) //Xét từng đề { //% Tạo đề thi thứ nhất bgWorker1.ReportProgress((_iSoDe + 1) * 100 / iSoDe); iPhanTramCongViec = iPhanTramCongViec + 100 / iSoDe;//Cập nhật % hiện đã hoàn thành InfoTest.iDeThiDangTao = _iSoDe + 1; // docDeThiMau.Activate(); //Copy nội dung file mẫu docDeThiMau.Sections.First.Range.Copy(); //Paste vào tệp tin ĐỀ THI emptyDoc.Activate(); oRng = emptyDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oPara2 = emptyDoc.Content.Paragraphs.Add(ref oRng); oPara2.Range.PasteAndFormat(Microsoft.Office.Interop.Word.WdRecoveryType.wdFormatOriginalFormatting); //paste tiêu đề và giữa nguyên định dạng //Find and replace: sTenDe = InfoTest.DanhSachTenDeThi[_iSoDe]; //Lấy tên đề trong danh sách tên đề // while (sTenDe.Length < 2) { sTenDe = '0' + sTenDe; } this.FindAndReplace(wordApp, "$KYTHI$", sKyThi); this.FindAndReplace(wordApp, "$MONTHI$", sMonThi); this.FindAndReplace(wordApp, "$DOITUONG$", sDoiTuong); this.FindAndReplace(wordApp, "$HINHTHUCTHI$", sHinhThucThi); this.FindAndReplace(wordApp, "$THOIGIAN$", sThoiGian); this.FindAndReplace(wordApp, "$NGAYTHI$", sNgayThangNamThi); this.FindAndReplace(wordApp, "$MADE$", sTenDe.ToString()); //Paste vào tệp tin ĐÁP ÁN ĐỀ THI emptyDoc1.Activate(); oRng = emptyDoc1.Bookmarks.get_Item(ref oEndOfDoc).Range; oPara2 = emptyDoc1.Content.Paragraphs.Add(ref oRng); oPara2.Range.PasteAndFormat(Microsoft.Office.Interop.Word.WdRecoveryType.wdFormatOriginalFormatting); //paste tiêu đề và giữa nguyên định dạng //Find and replace: sTenDe = InfoTest.DanhSachTenDeThi[_iSoDe]; //Lấy tên đề trong danh sách tên đề // while (sTenDe.Length < 3) { sTenDe = '0' + sTenDe; } this.FindAndReplace(wordApp, "$KYTHI$", sKyThi); this.FindAndReplace(wordApp, "$MONTHI$", sMonThi); this.FindAndReplace(wordApp, "$DOITUONG$", sDoiTuong); this.FindAndReplace(wordApp, "$HINHTHUCTHI$", sHinhThucThi); this.FindAndReplace(wordApp, "$THOIGIAN$", sThoiGian); this.FindAndReplace(wordApp, "$NGAYTHI$", sNgayThangNamThi); this.FindAndReplace(wordApp, "$MADE$", sTenDe.ToString()); //Paste nội dung chi tiết for (int i = 0; i < InfoTest.DanhSachNhomCauHoi.Count; i++) //Mở từng nhóm file { object _fileNhom = InfoTest.DanhSachNhomCauHoi[i].DuongDan; //Lấy đường dẫn nhóm file Word.Document docNhom = null; docNhom = wordApp.Documents.Open(ref _fileNhom, ref missing, ref readOnly, 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); docNhom.Activate(); //---------------Paste ĐỀ THI List <int> tt = (List <int>)dsCauHoiBoDe[i]; docNhom.Tables[tt[_iSoDe]].Rows[1].Cells[1].Range.Copy();//Lấy cùng vị trí câu trong từng nhóm câu hỏi // Select the last table. // For this demo, the table has size of 3*4 (row * column). int totalTables = emptyDoc.Tables.Count; Microsoft.Office.Interop.Word.Table tab = emptyDoc.Tables[totalTables]; Microsoft.Office.Interop.Word.Range range = tab.Range; // Moves the cursor to the first cell of target row. range.Start = tab.Rows[tab.Rows.Count].Cells[1].Range.Start; range.End = range.Start; // Paste values to target row. range.Paste(); // Insert a new row after the last row. if (i != InfoTest.DanhSachNhomCauHoi.Count - 1) { tab.Rows.Add(ref missing); } //-------------Kết thúc Paste ĐỀ THI //------------------------------------------------- //---------------Paste ĐÁP ÁN ĐỀ THI List <int> tt1 = (List <int>)dsCauHoiBoDe[i]; docNhom.Tables[tt1[_iSoDe]].Range.Copy();//Lấy cùng vị trí câu trong từng nhóm câu hỏi // Select the last table. // For this demo, the table has size of 3*4 (row * column). int totalTables1 = emptyDoc1.Tables.Count; Microsoft.Office.Interop.Word.Table tab1 = emptyDoc1.Tables[totalTables]; Microsoft.Office.Interop.Word.Range range1 = tab1.Range; // Moves the cursor to the first cell of target row. range1.Start = tab1.Rows[tab1.Rows.Count].Cells[1].Range.Start; range1.End = range1.Start; // Paste values to target row. range1.Paste(); //-------------Kết thúc Paste ĐÁP ÁN ĐỀ THI // #region "Sao chép chỉ nội dung của cell" //List<int> tt = (List<int>)dsCauHoiBoDe[i]; //var copyFrom = docNhom.Tables[tt[_iSoDe]].Rows[1].Cells[1].Range;//Lấy cùng vị trí câu trong từng nhóm câu hỏi //int start = emptyDoc.Content.End - 1; //int end = emptyDoc.Content.End; //var copyTo = emptyDoc.Range(start, end); //copyFrom.MoveEnd(Microsoft.Office.Interop.Word.WdUnits.wdCharacter, -1); //copyTo.FormattedText = copyFrom.FormattedText; #endregion //----------------ĐỀ THI_Thay thế chữ "Câu hỏi" bằng "Câu 1 (2 điểm)" string tenCauHoi = ""; int tenCau; tenCau = i + 1; tenCauHoi = InfoTest.sTenCau + " " + tenCau.ToString() + " (" + InfoTest.DanhSachNhomCauHoi[i].Diem + " điểm)"; emptyDoc.Activate(); this.FindAndReplace(wordApp, "Câu hỏi", tenCauHoi); //-------------------ĐỀ THI-kết thúc //----------------ĐÁP ÁN ĐỀ THI_Thay thế chữ "Câu hỏi" bằng "Câu 1 (2 điểm)" emptyDoc1.Activate(); this.FindAndReplace(wordApp, "Câu hỏi", tenCauHoi); //-------------------ĐÁP ÁN ĐỀ THI-kết thúc ////Thêm 1 mark dòng //copyTo.InsertParagraphAfter(); //copyTo.SetRange(end, end); //Close Document: docNhom.Close(ref missing, ref missing, ref missing); //Kết thúc đọc file nhóm } //-----------ĐỀ THI - Thêm giải thích oRng = emptyDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; if (InfoTest.sGiaiThich != "") //Nếu có thêm giải thích { oPara = emptyDoc.Content.Paragraphs.Add(ref oRng); //add paragraph at end of document //oPara.Range.Font.Name = "Arial"; oPara.Range.Text = InfoTest.sGiaiThich; //"Không được sử dụng tài liệu"; //add some text in paragraph oPara.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; oPara.Range.Font.Bold = 1; oPara.Format.SpaceAfter = 10; //define some style oPara.Range.InsertParagraphAfter(); } if (_iSoDe != iSoDe - 1) { ////Thêm 1 ngắt trang, chuyển sang đề tiếp theo wrdRng = emptyDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; wrdRng.InsertBreak(ref oPageBreak); } //-------------kết thúc ĐỀ THI - Thêm giải thích //-----------ĐÁP ÁN ĐỀ THI - Thêm giải thích oRng = emptyDoc1.Bookmarks.get_Item(ref oEndOfDoc).Range; if (InfoTest.sGiaiThich != "") //Nếu có thêm giải thích { oPara = emptyDoc1.Content.Paragraphs.Add(ref oRng); //add paragraph at end of document //oPara.Range.Font.Name = "Arial"; oPara.Range.Text = InfoTest.sGiaiThich; //"Không được sử dụng tài liệu"; //add some text in paragraph oPara.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; oPara.Range.Font.Bold = 1; oPara.Format.SpaceAfter = 10; //define some style oPara.Range.InsertParagraphAfter(); } if (_iSoDe != iSoDe - 1) { ////Thêm 1 ngắt trang, chuyển sang đề tiếp theo wrdRng = emptyDoc1.Bookmarks.get_Item(ref oEndOfDoc).Range; wrdRng.InsertBreak(ref oPageBreak); } //-------------kết thúc ĐÁP ÁN ĐỀ THI - Thêm giải thích } //Save as: filename ĐỀ THI if (!System.IO.Directory.Exists(InfoTest.sViTriLuuDeThi)) { InfoTest.sViTriLuuDeThi = InfoTest.sThuMucGoc; } string name = sMonThi + string.Format("{0: ddMMyyyyhhmmss}", DateTime.Now); object saveAs = InfoTest.sViTriLuuDeThi + "\\" + name + ".docx"; emptyDoc.SaveAs2(ref saveAs, 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); emptyDoc.Close(ref missing, ref missing, ref missing); //Save as: filename ĐÁP ÁN ĐỀ THI object saveAs1 = InfoTest.sViTriLuuDeThi + "\\" + name + "_dap_an" + ".docx"; emptyDoc1.SaveAs2(ref saveAs1, 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); emptyDoc1.Close(ref missing, ref missing, ref missing); // docDeThiMau.Close(); //Đóng đề thi mẫu wordApp.Quit(); //Thoát MS Word } } catch (Exception ex) { MessageBox.Show("Lỗi 1: " + ex.Message + " source:" + ex.Source); } finally { processesaftergen = getRunningProcesses(); killProcesses(processesbeforegen, processesaftergen); } }
public void exportToWord(DataGridView DGV, string filename, string name) { 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 (int c = 0; c <= ColumnCount - 1; c++) { for (r = 0; r <= RowCount - 1; r++) { DataArray[r, c] = DGV.Rows[r].Cells[c].Value; } //end row loop } //end column loop Microsoft.Office.Interop.Word.Document oDoc = new Microsoft.Office.Interop.Word.Document(); oDoc.Application.Visible = true; oDoc.PageSetup.Orientation = Microsoft.Office.Interop.Word.WdOrientation.wdOrientLandscape; dynamic oRange = oDoc.Content.Application.Selection.Range; string oTemp = ""; for (r = 0; r <= RowCount - 1; r++) { for (int c = 0; c <= ColumnCount - 1; c++) { oTemp = oTemp + DataArray[r, c] + "\t"; } } oRange.Text = oTemp; object oMissing = Missing.Value; object Separator = Microsoft.Office.Interop.Word.WdTableFieldSeparator.wdSeparateByTabs; object ApplyBorders = true; object AutoFit = true; object AutoFitBehavior = Microsoft.Office.Interop.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(); 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; for (int c = 0; c <= ColumnCount - 1; c++) { oDoc.Application.Selection.Tables[1].Cell(1, c + 1).Range.Text = DGV.Columns[c].HeaderText; } oDoc.Application.Selection.Tables[1].Rows[1].Select(); oDoc.Application.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; foreach (Microsoft.Office.Interop.Word.Section section in oDoc.Application.ActiveDocument.Sections) { Microsoft.Office.Interop.Word.Range headerRange = section.Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range; headerRange.Fields.Add(headerRange, Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage); headerRange.Text = name; headerRange.Font.Size = 16; headerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; } oDoc.SaveAs(filename, 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); } }
private void button1_Click(object sender, RoutedEventArgs e) { var word_app = new Word.Application { Visible = false }; // Создаем документ Word. object missing = Type.Missing; var word_doc = word_app.Documents.Add(); // Создаем абзац заголовка. var para = word_doc.Paragraphs.Add(ref missing); object style_name = "Заголовок 1"; para.Range.set_Style(ref style_name); para.Range.Text += "Кривая хризантемы"; para.Range.InsertParagraphAfter(); //Добавление верхнего колонтитула foreach (Microsoft.Office.Interop.Word.Section section in word_doc.Sections) { Microsoft.Office.Interop.Word.Range headerRange = section.Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range; headerRange.Fields.Add(headerRange, Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage); headerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; headerRange.Font.ColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdBlue; headerRange.Font.Size = 10; headerRange.Text = "Верхний колонтитул" + Environment.NewLine + "www.CSharpCoderR.com"; } para.Range.Font.Size = 13; para.Range.Font.Bold = -1; richTextBox.SelectAll(); string myText = richTextBox.Selection.Text; para.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; para.Range.Text += richTextBox.Selection.Text; para.Range.InsertParagraphAfter(); para.Range.Font.Italic = -1; para.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft; para.Range.Text += richTextBox.Selection.Text; para.Range.InsertParagraphAfter(); para.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight; para.Range.Text += richTextBox.Selection.Text; para.Range.InsertParagraphAfter(); //richTextBox1.Selection.Text = para.Range.Text; //Set myRange = ActiveDocument.Words(1) //para.Range.Words(1) = "Dear "; SAVE(word_doc, word_app); }
private void WordAction(IWebSocketConnection webSocket, JObject action) { var wordAction = action["command"].Value <string>(); switch (wordAction) { case "open": { wordApp = new Word.Application(); wordApp.Visible = true; JObject res = new JObject(); res["action"] = "word"; res["result"] = "OK"; webSocket.Send(res.ToString()); } break; case "close": { wordApp.Quit(); Marshal.FinalReleaseComObject(wordApp); wordApp = null; JObject res = new JObject(); res["action"] = "word"; res["result"] = "OK"; webSocket.Send(res.ToString()); } break; case "settext": { //Create a missing variable for missing value object missing = System.Reflection.Missing.Value; //Create a new document var document = wordApp.Documents.Add(ref missing, ref missing, ref missing, ref missing); //Add header into the document foreach (Microsoft.Office.Interop.Word.Section section in document.Sections) { //Get the header range and add the header details. Microsoft.Office.Interop.Word.Range headerRange = section.Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range; headerRange.Fields.Add(headerRange, Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage); headerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; headerRange.Font.ColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdBlue; headerRange.Font.Size = 10; headerRange.Text = "Header text goes here"; } //Add the footers into the document foreach (Microsoft.Office.Interop.Word.Section wordSection in document.Sections) { //Get the footer range and add the footer details. Microsoft.Office.Interop.Word.Range footerRange = wordSection.Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range; footerRange.Font.ColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdDarkRed; footerRange.Font.Size = 10; footerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; footerRange.Text = "Footer text goes here"; } //adding text to document document.Content.SetRange(0, 0); document.Content.Text = "This is test document " + action["text"].Value <string>() + Environment.NewLine; JObject res = new JObject(); res["action"] = "word"; res["result"] = "OK"; webSocket.Send(res.ToString()); } break; } }
public void GetNewReport(DataTable dt) { object oMissing = System.Reflection.Missing.Value; object unknow = Type.Missing; object start = 0; object end = 0; Microsoft.Office.Interop.Word.Range tableLocation = ActiveDocumentManager.getDefaultAD().Range(ref start, ref end); // 添加页眉 emrTaskPane.wordApp.ActiveWindow.View.Type = Word.WdViewType.wdOutlineView; emrTaskPane.wordApp.ActiveWindow.View.SeekView = Word.WdSeekView.wdSeekPrimaryHeader; emrTaskPane.wordApp.ActiveWindow.ActivePane.Selection.InsertAfter(""); emrTaskPane.wordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight; //设置右对齐 emrTaskPane.wordApp.ActiveWindow.View.SeekView = Word.WdSeekView.wdSeekMainDocument; //跳出页眉设置 emrTaskPane.wordApp.Selection.ParagraphFormat.LineSpacing = 15f; //设置文档的行间距 //移动焦点并换行 object count = 14; object WdLine = Microsoft.Office.Interop.Word.WdUnits.wdLine; //换一行; emrTaskPane.wordApp.Selection.MoveDown(ref WdLine, ref count, ref unknow); //移动焦点 emrTaskPane.wordApp.Selection.MoveDown(ref WdLine, ref count, ref unknow); //移动焦点 emrTaskPane.wordApp.Selection.TypeParagraph(); //插入段落 Word.Range range = ActiveDocumentManager.getDefaultAD().Paragraphs.Last.Range; range.Start = ActiveDocumentManager.getDefaultAD().Paragraphs.Last.Range.End; range.Select(); ///range.Text = "终末病历质量评分汇总表" + "(" + comboBox2.Text + "年" + comboBox1.Text + "月)"; range.Text = "终末病历质量评分汇总表"; range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; range.Font.Name = "黑体"; range.Font.Size = 14.5f; range.Start = range.End; range.Select(); Microsoft.Office.Interop.Word.Table newTable = ActiveDocumentManager.getDefaultAD().Tables.Add(emrTaskPane.wordApp.Selection.Range, dt.Rows.Count + 1, 8, ref unknow, ref unknow); //设置表格样式 newTable.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle; newTable.Borders.InsideLineStyle = Word.WdLineStyle.wdLineStyleSingle; emrTaskPane.wordApp.Selection.ParagraphFormat.LineSpacing = 15f;//设置文档的行间距 newTable.Cell(1, 1).Range.Text = "出院日期"; newTable.Cell(1, 1).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; newTable.Cell(1, 2).Range.Text = "科室"; newTable.Cell(1, 2).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; newTable.Cell(1, 3).Range.Text = "主管医师"; newTable.Cell(1, 3).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; newTable.Cell(1, 4).Range.Text = "病案号"; newTable.Cell(1, 4).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; newTable.Cell(1, 5).Range.Text = "扣分原因"; newTable.Cell(1, 5).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; newTable.Cell(1, 6).Range.Text = "扣分"; newTable.Cell(1, 6).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; newTable.Cell(1, 7).Range.Text = "得分"; newTable.Cell(1, 7).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; newTable.Cell(1, 8).Range.Text = "病历级别"; newTable.Cell(1, 8).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; newTable.Columns[1].Width = 40f; newTable.Columns[2].Width = 36f; newTable.Columns[3].Width = 45f;//能显示三个字 newTable.Columns[4].Width = 43f; newTable.Columns[5].Width = 150f; newTable.Columns[6].Width = 40f; newTable.Columns[7].Width = 40f; newTable.Columns[8].Width = 36f; if (dt.Rows.Count > 0) { for (int i = 0; i < dt.Rows.Count; i++) { newTable.Cell(i + 2, 1).Range.Text = dt.Rows[i]["出院日期"].ToString(); newTable.Cell(i + 2, 1).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; newTable.Cell(i + 2, 2).Range.Text = dt.Rows[i]["科室"].ToString(); newTable.Cell(i + 2, 2).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; newTable.Cell(i + 2, 3).Range.Text = dt.Rows[i]["主管医师"].ToString(); newTable.Cell(i + 2, 3).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; newTable.Cell(i + 2, 4).Range.Text = dt.Rows[i]["病案号"].ToString(); newTable.Cell(i + 2, 4).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; newTable.Cell(i + 2, 5).Range.Text = dt.Rows[i]["扣分原因"].ToString(); newTable.Cell(i + 2, 5).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft; newTable.Cell(i + 2, 6).Range.Text = dt.Rows[i]["扣分"].ToString(); newTable.Cell(i + 2, 6).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; newTable.Cell(i + 2, 7).Range.Text = dt.Rows[i]["得分"].ToString(); newTable.Cell(i + 2, 7).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; newTable.Cell(i + 2, 8).Range.Text = dt.Rows[i]["病历级别"].ToString(); newTable.Cell(i + 2, 8).Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; } } object Line1 = Microsoft.Office.Interop.Word.WdUnits.wdLine;//换一行; //object WdLine = Microsoft.Office.Interop.Word.WdUnits.wdLine;//换一行; emrTaskPane.wordApp.Selection.MoveDown(ref Line1, ref count, ref unknow); //移动焦点 emrTaskPane.wordApp.Selection.MoveDown(ref Line1, ref count, ref unknow); //移动焦点 emrTaskPane.wordApp.Selection.TypeParagraph(); //插入段落 Word.Range range1 = ActiveDocumentManager.getDefaultAD().Paragraphs.Last.Range; range1.Start = ActiveDocumentManager.getDefaultAD().Paragraphs.Last.Range.End; range1.Select(); range1.Text = "记录数共计" + dt.Rows.Count.ToString() + "条"; range1.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight; range1.Font.Name = "黑体"; range1.Font.Size = 10f; range1.Start = range.End; //Globals.ThisAddIn.ShowNoteMenu(); //Globals.ThisAddIn.noteMenu.OperationEnableForStat(true); }
private void createWords() { int filesToCreateTemp = frm1.filesToCreate; // avoid change in '#files to be created' during runtime try { string workingDir = frm1.workingDirectory + "officeSimulation_word\\"; System.IO.Directory.CreateDirectory(workingDir); int documentCount = 0; string wordFileNameDate = frm1.wordFileName + DateTime.Now.ToString("dd-MM-yyyy_HH-mm"); string wordFileNameDateFinal; // ~~~~~~~~~~~~~~~~~~~~~~~~~~ Word instance ~~~~~~~~~~~~~~~~~~~~~~~~~ var winword = new Microsoft.Office.Interop.Word.Application(); winword.ShowAnimation = false; winword.Visible = false; object winWordMissing = System.Reflection.Missing.Value; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ while (documentCount < filesToCreateTemp) { wordFileNameDateFinal = wordFileNameDate + "_" + documentCount; // ~~~~~~ create word files (vary formatting) try { if (frm1.varyFormatting) { //Selecting random lorem text length Random r = new Random(DateTime.Now.Millisecond); int rLorem1 = r.Next(0, 5); int rLorem2 = r.Next(0, 5); int rLorem3 = r.Next(0, 5); int rLorem4 = r.Next(0, 2); int rLorem5 = r.Next(0, 2); //Create a new document Microsoft.Office.Interop.Word.Document document = winword.Documents.Add(ref winWordMissing, ref winWordMissing, ref winWordMissing, ref winWordMissing); //Add header into the document foreach (Microsoft.Office.Interop.Word.Section section in document.Sections) { //Get the header range and add the header details. Microsoft.Office.Interop.Word.Range headerRange = section.Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range; headerRange.Fields.Add(headerRange, Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage); headerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; headerRange.Font.ColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdBlue; headerRange.Font.Size = 10; headerRange.Text = frm1.lorems[rLorem4]; } //Add the footers into the document foreach (Microsoft.Office.Interop.Word.Section wordSection in document.Sections) { //Get the footer range and add the footer details. Microsoft.Office.Interop.Word.Range footerRange = wordSection.Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range; footerRange.Font.ColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdDarkRed; footerRange.Font.Size = 10; footerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; footerRange.Text = frm1.lorems[rLorem5]; } //adding text to document document.Content.SetRange(0, 0); document.Content.Text = frm1.lorems[rLorem1] + "\r\n"; // adding some delay if (frm1.addDelay) { Thread.Sleep(frm1.addDelaySec * 1000); } document.Content.Text = frm1.lorems[rLorem2] + "\r\n"; document.Content.Text = frm1.lorems[rLorem3]; //Add paragraph with Heading 1 style Microsoft.Office.Interop.Word.Paragraph para1 = document.Content.Paragraphs.Add(ref winWordMissing); object styleHeading1 = "Heading 1"; para1.Range.set_Style(ref styleHeading1); para1.Range.Text = frm1.lorems[rLorem1]; para1.Range.InsertParagraphAfter(); //Add paragraph with Heading 2 style Microsoft.Office.Interop.Word.Paragraph para2 = document.Content.Paragraphs.Add(ref winWordMissing); object styleHeading2 = "Heading 2"; para2.Range.set_Style(ref styleHeading2); para2.Range.Text = frm1.lorems[rLorem2]; para2.Range.InsertParagraphAfter(); //Save the document object filename = workingDir + wordFileNameDateFinal + ".docx"; //object filename = filePath + "\\" + fileName + ".docx"; document.SaveAs2(ref filename); // Keeping a list of files created frm1.listOfWordFiles.Add(filename.ToString()); document.Close(ref winWordMissing, ref winWordMissing, ref winWordMissing); document = null; if (document != null) { Marshal.ReleaseComObject(document); } } else // ~~~~~~ create word files (NO formatting) { //adding text to document Random r = new Random(DateTime.Now.Millisecond); int rLorem1 = r.Next(0, 5); int rLorem2 = r.Next(0, 5); int rLorem3 = r.Next(0, 5); //Create a new document Microsoft.Office.Interop.Word.Document document = winword.Documents.Add(ref winWordMissing, ref winWordMissing, ref winWordMissing, ref winWordMissing); document.Content.SetRange(0, 0); document.Content.Text = frm1.lorems[rLorem1] + "\r\n"; // adding some delay if (frm1.addDelay) { Thread.Sleep(frm1.addDelaySec * 1000); } document.Content.Text = frm1.lorems[rLorem2] + "\r\n"; document.Content.Text = frm1.lorems[rLorem3]; //Save the document object filename = workingDir + wordFileNameDateFinal + ".docx"; //object filename = filePath + "\\" + fileName + ".docx"; document.SaveAs2(ref filename); // Keeping a list of files created frm1.listOfWordFiles.Add(filename.ToString()); document.Close(ref winWordMissing, ref winWordMissing, ref winWordMissing); document = null; if (document != null) { Marshal.ReleaseComObject(document); } } } catch (Exception ex) { Console.WriteLine("Error creating Word file!"); Console.WriteLine(ex.Message); } documentCount++; } // ~~~~~~ copy some of the documents int i2 = 0; while (i2 < filesToCreateTemp) { if (i2 % 4 == 0) { string filePathNoExtension = frm1.listOfWordFiles[i2].Substring(0, frm1.listOfWordFiles[i2].Length - 5); string newFilePathCopy = filePathNoExtension + "_copy" + ".docx"; try { var originalDocument = winword.Documents.Open(frm1.listOfWordFiles[i2]); // Open original document originalDocument.ActiveWindow.Selection.WholeStory(); // Select all in original document var originalText = originalDocument.ActiveWindow.Selection; // Copy everything to the variable var newDocument = new Word.Document(); // Create new Word document newDocument.Range().Text = originalText.Text; // Pasete everything from the variable newDocument.SaveAs(newFilePathCopy); // maybe SaveAs2?? // Save the new document originalDocument.Close(false); newDocument.Close(); if (originalDocument != null) { Marshal.ReleaseComObject(originalDocument); } if (newDocument != null) { Marshal.ReleaseComObject(newDocument); } } catch (Exception ex) { Console.WriteLine("Error coping documents"); Console.WriteLine(ex.Message); } } i2++; } // ~~~~~~ find-replace in some documents int i3 = 0; while (i3 < filesToCreateTemp) { if (i3 % 3 == 0) { try { Microsoft.Office.Interop.Word.Document aDoc = winword.Documents.Open(frm1.listOfWordFiles[i3], ReadOnly: false, Visible: false); aDoc.Activate(); winword.Selection.Find.Execute(frm1.textToSearch1, false, true, false, false, false, true, 1, false, frm1.textToReplace1, 2, false, false, false, false); winword.Selection.Find.Execute(frm1.textToSearch2, false, true, false, false, false, true, 1, false, frm1.textToReplace2, 2, false, false, false, false); aDoc.SaveAs2(); aDoc.Close(ref winWordMissing, ref winWordMissing, ref winWordMissing); aDoc = null; if (aDoc != null) { Marshal.ReleaseComObject(aDoc); } } catch (Exception ex) { Console.WriteLine("Error in find-replace"); Console.WriteLine(ex.Message); } } i3++; } // ~~~~~~~~~~~~~~~~~~~~ Terminating Word instance ~~~~~~~~~~~~~~~~~~~ winword.Quit(ref winWordMissing, ref winWordMissing, ref winWordMissing); winword.Quit(); if (winword != null) { Marshal.ReleaseComObject(winword); } winword = null; winWordMissing = null; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ } catch (Exception ex) { Console.WriteLine("backGroundWorker WordCreate Error"); Console.WriteLine(ex.Message); } tskCreateWordsRunning = false; Console.WriteLine(); Console.WriteLine("runEverything(): createWords() -> DONE"); }
private void CreateDocument() { try { Microsoft.Office.Interop.Word.Application winword = new Microsoft.Office.Interop.Word.Application(); winword.Visible = false; object missing = System.Reflection.Missing.Value; Microsoft.Office.Interop.Word.Document document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing); foreach (Microsoft.Office.Interop.Word.Section section in document.Sections) { Microsoft.Office.Interop.Word.Range headerRange = section.Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range; headerRange.Fields.Add(headerRange, Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage); headerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; headerRange.Font.ColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdBlue; headerRange.Font.Size = 10; headerRange.Text = "Header text goes here"; } foreach (Microsoft.Office.Interop.Word.Section wordSection in document.Sections) { Microsoft.Office.Interop.Word.Range footerRange = wordSection.Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range; footerRange.Font.ColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdDarkRed; footerRange.Font.Size = 10; footerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; footerRange.Text = "Footer text goes here"; } document.Content.SetRange(0, 0); document.Content.Text = "This is test document " + Environment.NewLine; Microsoft.Office.Interop.Word.Paragraph para1 = document.Content.Paragraphs.Add(ref missing); object styleHeading1 = "Heading 1"; para1.Range.set_Style(ref styleHeading1); para1.Range.Text = "Para 1 text"; para1.Range.InsertParagraphAfter(); Microsoft.Office.Interop.Word.Paragraph para2 = document.Content.Paragraphs.Add(ref missing); object styleHeading2 = "Heading 2"; para2.Range.set_Style(ref styleHeading2); para2.Range.Text = "Neve: #NEV#"; para2.Range.InsertParagraphAfter(); Word.Table firstTable = document.Tables.Add(para1.Range, 3, 2, ref missing, ref missing); firstTable.Borders.Enable = 1; foreach (Row row in firstTable.Rows) { foreach (Cell cell in row.Cells) { if (cell.RowIndex == 1) { cell.Range.Text = "Column " + cell.ColumnIndex.ToString(); cell.Range.Font.Bold = 1; cell.Range.Font.Name = "verdana"; cell.Range.Font.Size = 10; cell.Shading.BackgroundPatternColor = WdColor.wdColorGray25; cell.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; cell.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; } else { cell.Range.Text = "Tartalom " + (cell.RowIndex - 2 + cell.ColumnIndex).ToString(); } } } object filename = @"d:\temp1.docx"; document.SaveAs(ref filename); document.Close(ref missing, ref missing, ref missing); document = null; winword.Quit(ref missing, ref missing, ref missing); winword = null; System.Windows.Forms.MessageBox.Show("Document created successfully !"); } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } }