public WordActiveDocument(IOfficeApplication application, MsWord._Document document) : base(application, document.FullName) { _document = document; InitializeWsDocument(FullPath); }
public override void Dispose() { if (_document != null) { Marshal.ReleaseComObject(_document); _document = null; } }
public FontSelection(Word._Application WordApp, string fname) { object oMissing = System.Reflection.Missing.Value; oWord = WordApp; object fileName = fname; object oReadOnly = (Boolean)true; object oVisible = (Boolean)true; oDoc = oWord.Documents.Open(ref fileName, ref oMissing, ref oReadOnly, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oVisible, ref oMissing, ref oMissing, ref oMissing, ref oMissing); make_font_table(fname); InitializeComponent(); }
// конструктор, создаем по шаблону, потом возможно расширение другими вариантами public word() { wordApplication = new Word.Application(); //создаем ноый документ методом приложения Word по поути к шаблону документа try { wordDocument = wordApplication.Documents.Add(ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing); } // если произошла ошибка, то приложение Word надо закрыть catch (Exception error) { wordApplication.Quit(ref wordMissing, ref wordMissing, ref wordMissing); wordApplication = null; throw new Exception("Ошибка. Не удалось открыть шаблон документа MS Word. " + error.Message); } // завершение createFromTemplate(string templatePath) }
/// <summary> /// Generate word document with register of system documents /// </summary> /// <param name="tv"></param> public string RegisterOfSytemDocumentsXXX(TreeView tv, string clientFolder, string clientName, string processName, string userID) { object oMissing = System.Reflection.Missing.Value; var pastPlannedActivities = string.Empty; //Start Word and create a new document. WordNet._Application oWord = new Application { Visible = false }; WordNet._Document oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); oDoc.PageSetup.Orientation = WordNet.WdOrientation.wdOrientLandscape; //PrintToWord(oDoc, "Register of System Documents", 16, 0, FCMWordAlign.CENTER); //PrintToWord(oDoc, " ", 8, 0); // Locate client folder // string clientFileLocationName = Utils.getFilePathName(@"%TEMPLATEFOLDER%\ClientSource\", "ROS-001 Register Of System Documents.doc"); FullFileNamePath = clientFileLocationName; FileName = "RegisterOfSystemDocuments.doc"; if (File.Exists(clientFileLocationName)) { // Delete file try { File.Delete(clientFileLocationName); uioutput.AddOutputMessage("File replaced: " + clientFileLocationName, processName: processName, userID: userID); } catch (Exception) { uioutput.AddOutputMessage("Error deleting file " + clientFileLocationName, processName: processName, userID: userID); uioutput.AddErrorMessage("Error deleting file " + clientFileLocationName, processName: processName, userID: userID); return(clientFileLocationName); } } // string filename = Path.Combine(Path.GetTempPath(), Path.ChangeExtension(Path.GetTempFileName(), "doc")); oDoc.SaveAs(clientFileLocationName); string msg = ">>> Generating file... "; if (uioutput != null) { uioutput.AddOutputMessage(msg, processName: processName, userID: userID); } PrintToWord(oDoc, " ", 8, 1); WordNet.Range wrdRng; WordNet.Table oTable; wrdRng = oDoc.Bookmarks.get_Item(oEndOfDoc).Range; int rowCount = 30; foreach (Section wordSection in oDoc.Sections) { HeaderFooter footer = wordSection.Footers.Item(Word.WdHeaderFooterIndex.wdHeaderFooterPrimary); footer.Range.Select(); footer.Range.Text = FullFileNamePath; footer.PageNumbers.Add(); HeaderFooter header = wordSection.Headers.Item(Word.WdHeaderFooterIndex.wdHeaderFooterPrimary); header.Range.Select(); //header.Range.Text = client.Name + " Register of System Documents " ; header.Range.Font.Size = 20; header.Range.Cells.Add(client.Name); header.Range.Cells.Add("Register of System Documents"); oWord.Selection.Paragraphs [1].Alignment = WordNet.WdParagraphAlignment.wdAlignParagraphLeft; } // Get number of rows for a client document, client document set // var cds = new BUSClientDocumentSet(Utils.ClientID, Utils.ClientSetID); rowCount = cds.DocumentCount; if (rowCount < 1) { return(clientFileLocationName); } oTable = oDoc.Tables.Add(wrdRng, rowCount, 8, ref vkFalse, ref vkFalse); oTable.Borders.OutsideColor = WordNet.WdColor.wdColorBlack; oTable.Borders.InsideLineStyle = WordNet.WdLineStyle.wdLineStyleDouble; oTable.Borders.OutsideColor = WordNet.WdColor.wdColorBlueGray; oTable.Borders.OutsideLineStyle = WordNet.WdLineStyle.wdLineStyleEmboss3D; //oTable.Borders.InsideLineWidth = WordNet.WdLineWidth.wdLineWidth050pt; //oTable.Borders.OutsideLineWidth = WordNet.WdLineWidth.wdLineWidth025pt; //oTable.Borders.InsideColor = WordNet.WdColor.wdColorAutomatic; //oTable.Borders.OutsideColor = WordNet.WdColor.wdColorAutomatic; oTable.Rows [1].HeadingFormat = -1; WordNet.Row headingRow = oTable.Rows [1]; ApplyHeadingStyle(headingRow.Cells [1], 200); headingRow.Cells [1].Range.Text = "Directory"; ApplyHeadingStyle(headingRow.Cells [2], 60); headingRow.Cells [2].Range.Text = "Sub Directory"; ApplyHeadingStyle(headingRow.Cells [3], 80); headingRow.Cells [3].Range.Text = "Document Number"; ApplyHeadingStyle(headingRow.Cells [4], 30); headingRow.Cells [4].Range.Text = "Sml"; ApplyHeadingStyle(headingRow.Cells [5], 40); headingRow.Cells [5].Range.Text = "Med"; ApplyHeadingStyle(headingRow.Cells [6], 30); headingRow.Cells [6].Range.Text = "Lrg"; ApplyHeadingStyle(headingRow.Cells [7], 50); headingRow.Cells [7].Range.Text = "Version"; ApplyHeadingStyle(headingRow.Cells [8], 200); headingRow.Cells [8].Range.Text = "Document Name"; int line = 0; foreach (var treeNode in tv.Nodes) { line++; WriteLineToRoSD(tv.Nodes [0], oDoc, oTable, prefix: "", parent: "", seqnum: line); } msg = ">>> End "; if (uioutput != null) { uioutput.AddOutputMessage(msg, processName, userID); } PrintToWord(oDoc, " ", 12, 1); oDoc.Save(); oDoc.Close(); oWord.Visible = true; oWord.Documents.Open(FileName: clientFileLocationName); oWord.Activate(); return(clientFileLocationName); }
public void writeClass(DateTime dateFrom, DateTime dateTo, string nameFile, string NameReport, string Name, double Price, string NameCategory, string Description, int AmountStore, string sql) { try { Word._Application wordApplication = new Word.Application(); Word._Document wordDocument = null; var templatePathObj = Environment.CurrentDirectory + "\\" + nameFile + ".docx"; try { wordDocument = wordApplication.Documents.Add(templatePathObj); } catch { if (wordDocument != null) { wordDocument.Close(false); wordDocument = null; } wordApplication.Quit(); wordApplication = null; throw; } wordApplication.Visible = false; wordsWhoReplase(NameReport, Name, wordDocument, dateFrom, dateTo, templatePathObj, NameCategory, Price, AmountStore, Description); wordApplication.Selection.Find.Execute("{Table}"); Word.Range wordRange = wordApplication.Selection.Range; DataSet ds; outPutDataSet(out ds, sql); var wordTable = wordDocument.Tables.Add(wordRange, ds.Tables[0].Rows.Count + 1, 6); wordTable.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle; wordTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleDouble; wordTable.Cell(1, 1).Range.Text = "Название"; wordTable.Cell(1, 2).Range.Text = "УПН"; wordTable.Cell(1, 3).Range.Text = "Кол-во"; wordTable.Cell(1, 4).Range.Text = "Скидка"; wordTable.Cell(1, 5).Range.Text = "Общая цена"; wordTable.Cell(1, 6).Range.Text = "Дата покупки"; for (int i = 2; i < ds.Tables[0].Rows.Count + 2; i++) { for (int j = 0; j < 6; j++) { if (j == 5) { wordTable.Cell(i, j + 1).Range.Text = Convert.ToDateTime(ds.Tables[0].Rows[i - 2][j]).Date.ToString("d"); } else if (j == 4) { wordTable.Cell(i, j + 1).Range.Text = Math.Round(Convert.ToDouble(ds.Tables[0].Rows[i - 2][j])).ToString(); } else { wordTable.Cell(i, j + 1).Range.Text = ds.Tables[0].Rows[i - 2][j].ToString(); } } } wordApplication.Visible = true; } catch { } }
public void ToPdf() { bool occupy = true; System.Collections.Generic.List <string> strAry = new List <string>(); while (occupy) { try { using (File.Open(m_FilePathWord, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) { } occupy = false;//如果可以运行至此那么就是 } catch (IOException e) { strAry.Add(e.ToString()); Thread.Sleep(100); } } WORD.ApplicationClass wordApp = new WORD.ApplicationClass(); WORD._Document wordDoc = null; object paramSourceDoc = m_FilePathWord; object paramMissing = Type.Missing; string strPdf = m_FilePathWord.Substring(0, m_FilePathWord.LastIndexOf('.')); string paramExportFilePath = strPdf; WORD.WdExportFormat paramexportFormat = WORD.WdExportFormat.wdExportFormatPDF; bool paramOpenAfterExport = false; WORD.WdExportOptimizeFor parameExportOptimizeFor = WORD.WdExportOptimizeFor.wdExportOptimizeForPrint; WORD.WdExportRange parameExportRange = WORD.WdExportRange.wdExportAllDocument; int paramStartPage = 0; int paramEndPage = 0; WORD.WdExportItem paramExportItem = WORD.WdExportItem.wdExportDocumentContent; bool paramIncludeDocProps = true; bool paramKeepIRM = true; WORD.WdExportCreateBookmarks paramCreateBookMarks = WORD.WdExportCreateBookmarks.wdExportCreateWordBookmarks; bool paramDocStructureTags = true; bool paramBitmapMissingFonts = true; bool paramUseISO19005_1 = false; try { wordDoc = wordApp.Documents.Open( ref paramSourceDoc, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing ); if (wordDoc != null) { wordDoc.ExportAsFixedFormat(paramExportFilePath, paramexportFormat, paramOpenAfterExport, parameExportOptimizeFor, parameExportRange, paramStartPage, paramEndPage, paramExportItem, paramIncludeDocProps, paramKeepIRM, paramCreateBookMarks, paramDocStructureTags, paramBitmapMissingFonts, paramUseISO19005_1, ref paramMissing); } if (wordDoc != null) { wordDoc.Close(ref paramMissing, ref paramMissing, ref paramMissing); System.Runtime.InteropServices.Marshal.ReleaseComObject(wordDoc); } if (wordApp != null) { wordApp.Quit(ref paramMissing, ref paramMissing, ref paramMissing); System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp); } PostHttpMsg pm = new PostHttpMsg(); pm.DataPost = strPdf + ".pdf"; pm.PostMsg(); } catch (System.Exception ex) { ex.ToString(); } finally { wordDoc = null; wordApp = null; GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); } }
private void WriteLineToRoSD(TreeNode tn, WordNet._Document oDoc, WordNet.Table oTable, string prefix = "", string parent = "", int seqnum = 0) { if (tn.Tag == null || tn.Tag.GetType().Name != "scClientDocSetDocLink") { // still need to check subnodes } else { int x = 0; foreach (TreeNode node in tn.Nodes) { x++; row++; scClientDocSetDocLink documentClient = (scClientDocSetDocLink)node.Tag; string currentParent = ""; if (string.IsNullOrEmpty(parent)) { currentParent = x.ToString(); } else { currentParent = parent + "." + x.ToString(); } // First column oTable.Cell(row, 1).Width = 200; if (documentClient.document.RecordType == "FOLDER") { oTable.Cell(row, 1).Range.Text = documentClient.document.Name; } else { oTable.Cell(row, 1).Range.Text = ""; } oTable.Cell(row, 2).Width = 60; oTable.Cell(row, 2).Range.Text = ""; // Sub Directory oTable.Cell(row, 3).Width = 80; if (documentClient.document.RecordType == "DOCUMENT") { oTable.Cell(row, 3).Range.Text = prefix + documentClient.document.CUID; } else { oTable.Cell(row, 3).Range.Text = ""; } oTable.Cell(row, 4).Width = 30; oTable.Cell(row, 4).Range.Text = ""; // Sml oTable.Cell(row, 5).Width = 40; oTable.Cell(row, 5).Range.Text = ""; // Med oTable.Cell(row, 6).Width = 30; oTable.Cell(row, 6).Range.Text = ""; // Lrg oTable.Cell(row, 7).Width = 50; if (documentClient.document.RecordType == "DOCUMENT") { oTable.Cell(row, 7).Range.Text = prefix + documentClient.document.IssueNumber.ToString("000"); } else { oTable.Cell(row, 7).Range.Text = ""; } oTable.Cell(row, 8).Width = 200; if (documentClient.document.RecordType == "DOCUMENT") { oTable.Cell(row, 8).Range.Text = prefix + documentClient.document.SimpleFileName; } else { oTable.Cell(row, 8).Range.Text = ""; } if (uioutput != null) { uioutput.AddOutputMessage(documentClient.document.Name, "", ""); } if (node.Nodes.Count > 0) { WriteLineToRoSD(node, oDoc, oTable, prefix: "", parent: currentParent, seqnum: x); } } } }
public void writeClass(string nameFile, string sql, int id, DateTime day) { Word._Application wordApplication = new Word.Application(); Word._Document wordDocument = null; var templatePathObj = Environment.CurrentDirectory + "\\" + nameFile + ".docx"; try { wordDocument = wordApplication.Documents.Add(templatePathObj); } catch { if (wordDocument != null) { wordDocument.Close(false); wordDocument = null; } wordApplication.Quit(); wordApplication = null; throw; } wordApplication.Visible = false; try { wordApplication.Selection.Find.Execute("{Table}"); Word.Range wordRange = wordApplication.Selection.Range; DataSet ds = null; SqlConnection con = null; SqlCommand cmd; SqlDataAdapter adapter = null; try { con = new SqlConnection(AuthorizationSettings.connectionString); con.Open(); cmd = new SqlCommand(sql, con); adapter = new SqlDataAdapter(cmd); ds = new DataSet(); adapter.Fill(ds, "Storedb"); } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { adapter.Dispose(); con.Close(); con.Dispose(); } //outPutDataSet(out ds, sql); int rows = ds.Tables[0].Rows.Count + 2 + 1; int columns = 9; var wordTable = wordDocument.Tables.Add(wordRange, rows, columns); wordTable.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle; wordTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleDouble; wordTable.Cell(1, 1).Range.Text = "Наименование товара"; wordTable.Cell(1, 2).Range.Text = "Единица измерения"; wordTable.Cell(1, 3).Range.Text = "Количество"; wordTable.Cell(1, 4).Range.Text = "Цена"; wordTable.Cell(1, 5).Range.Text = "Стоимость"; wordTable.Cell(1, 6).Range.Text = "Ставка НДС, %"; wordTable.Cell(1, 7).Range.Text = "Сумма НДС, руб. коп."; wordTable.Cell(1, 8).Range.Text = "Стоимость с НДС"; wordTable.Cell(1, 9).Range.Text = "Примечание"; wordTable.Cell(2, 1).Range.Text = "1"; wordTable.Cell(2, 2).Range.Text = "2"; wordTable.Cell(2, 3).Range.Text = "3"; wordTable.Cell(2, 4).Range.Text = "4"; wordTable.Cell(2, 5).Range.Text = "5"; wordTable.Cell(2, 6).Range.Text = "6"; wordTable.Cell(2, 7).Range.Text = "7"; wordTable.Cell(2, 8).Range.Text = "8"; wordTable.Cell(2, 9).Range.Text = "9"; int Count = 0; double Price = 0; double SumPrice = 0; double SumHDSPrice = 0; for (int i = 3; i < rows; i++) { double Discount = Convert.ToDouble(ds.Tables[0].Rows[i - 3][5]) / 100; double CurrentPrice = Convert.ToDouble(ds.Tables[0].Rows[i - 3][4]) - (Convert.ToDouble(ds.Tables[0].Rows[i - 3][4]) * Discount); wordTable.Cell(i, 1).Range.Text = ds.Tables[0].Rows[i - 3][0].ToString(); wordTable.Cell(i, 2).Range.Text = ds.Tables[0].Rows[i - 3][1].ToString(); wordTable.Cell(i, 3).Range.Text = ds.Tables[0].Rows[i - 3][2].ToString(); wordTable.Cell(i, 4).Range.Text = (Math.Round(CurrentPrice / 1.2, 2)).ToString("0.00"); wordTable.Cell(i, 5).Range.Text = Math.Round(((Math.Round(CurrentPrice / 1.2, 2)) * Convert.ToInt32(ds.Tables[0].Rows[i - 3][2])), 2).ToString("0.00"); wordTable.Cell(i, 6).Range.Text = "20%"; wordTable.Cell(i, 7).Range.Text = Math.Round((Math.Round((CurrentPrice / 1.2 * 0.2), 2) * Convert.ToInt32(ds.Tables[0].Rows[i - 3][2])), 2).ToString("0.00"); wordTable.Cell(i, 8).Range.Text = Math.Round(CurrentPrice * Convert.ToInt32(ds.Tables[0].Rows[i - 3][2]), 2).ToString("0.00"); Count += Convert.ToInt32(ds.Tables[0].Rows[i - 3][2]); Price += Math.Round(((Math.Round(CurrentPrice / 1.2, 2)) * Convert.ToInt32(ds.Tables[0].Rows[i - 3][2])), 2); SumPrice += Math.Round((Math.Round((CurrentPrice / 1.2 * 0.2), 2) * Convert.ToInt32(ds.Tables[0].Rows[i - 3][2])), 2); SumHDSPrice += Math.Round(CurrentPrice * Convert.ToInt32(ds.Tables[0].Rows[i - 3][2]), 2); } wordTable.Cell(rows, 1).Range.Text = "ИТОГО"; wordTable.Cell(rows, 3).Range.Text = Count.ToString(); wordTable.Cell(rows, 5).Range.Text = Price.ToString(); wordTable.Cell(rows, 7).Range.Text = SumPrice.ToString(); wordTable.Cell(rows, 8).Range.Text = SumHDSPrice.ToString(); sql = "select FirmName, UNP, FirmLegalAddress, FirmAccountNumber,FirmBankDetails, FirmPhoneNumber from Firms where FirmID=" + id.ToString(); outPutDataSet(out ds, sql); try { СуммаПрописью.Валюта.убли.Пропись(Price * 20 / 100); ReplaceWordStub("{YNH}", ds.Tables[0].Rows[0][1].ToString(), wordDocument); ReplaceWordStub("{DD}", day.ToString("d").Split('.')[0], wordDocument); ReplaceWordStub("{MM}", day.ToString("d").Split('.')[1], wordDocument); ReplaceWordStub("{YY}", day.ToString("d").Split('.')[2], wordDocument); ReplaceWordStub("{adress}", ds.Tables[0].Rows[0][0].ToString() + ds.Tables[0].Rows[0][2].ToString(), wordDocument); ReplaceWordStub("{SumHdsP}", СуммаПрописью.Валюта.убли.Пропись(SumPrice), wordDocument); ReplaceWordStub("{TotalSumP}", СуммаПрописью.Валюта.убли.Пропись(SumHDSPrice), wordDocument); } catch { } } catch (Exception ex) { MessageBox.Show(ex.Message); } wordApplication.Visible = true; }
private void ButtonPrintLetterBox_Click(object sender, RoutedEventArgs e) { try { if (TextBlockDataFilePatch.Text == "") { return; } if (TextBlockTemplateLetterPatch.Text == "") { return; } FileInfo fiDataFilePatch = new FileInfo(TextBlockDataFilePatch.Text); FileInfo fiTemplateFilePatch = new FileInfo(TextBlockTemplateLetterPatch.Text); if (fiDataFilePatch.Exists && fiTemplateFilePatch.Exists) { Excel.Application excel = new Excel.Application(); Excel.Workbook wbv = excel.Workbooks.Open(TextBlockDataFilePatch.Text, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0); Excel.Worksheet wx = (Excel.Worksheet)wbv.Worksheets.get_Item(1); Word._Application word = new Word.Application(); Word._Application word2 = new Word.Application(); //oDoc.Activate(); Word.Document wordFile = word.Documents.Open(TextBlockTemplateLetterPatch.Text); // word.Documents.Add(); int i = Convert.ToInt32(TextBoxNumberFrom.Text.ToString()); wordFile.FormFields["ТекстовоеПоле1"].Range.Text = wx.Cells[i, 4].Text; wordFile.FormFields["ТекстовоеПоле2"].Range.Text = wx.Cells[i, 2].Text; wordFile.FormFields["ТекстовоеПоле3"].Range.Text = wx.Cells[i, 8].Text; wordFile.FormFields["ТекстовоеПоле4"].Range.Text = wx.Cells[i, 13].Text; wordFile.FormFields["ТекстовоеПоле5"].Range.Text = wx.Cells[i, 12].Text; wordFile.FormFields["ТекстовоеПоле6"].Range.Text = wx.Cells[i, 13].Text; object oEndofDoc = "\\endofdoc"; object oRng = wordFile.Bookmarks.get_Item(ref oEndofDoc).Range; Word.Paragraph par = wordFile.Content.Paragraphs.Add(ref oRng); object unit; object extend; unit = Word.WdUnits.wdStory; extend = Word.WdMovementType.wdMove; word.Selection.EndKey(ref unit, ref extend); object oType; oType = Word.WdBreakType.wdSectionBreakNextPage; word.Selection.InsertBreak(ref oType); oRng = wordFile.Bookmarks.get_Item(ref oEndofDoc).Range; par = wordFile.Content.Paragraphs.Add(ref oRng); object missing = System.Reflection.Missing.Value; object readOnly = true; //word.Visible = true; int N = Convert.ToInt32(TextBoxNumberBefor.Text.ToString()); for (i++; i <= N; i++) { Word._Document oDoc = word2.Documents.Open(TextBlockTemplateLetterPatch.Text, 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.Range oRange = oDoc.Content; oDoc.FormFields["ТекстовоеПоле1"].Range.Text = wx.Cells[i, 4].Text; oDoc.FormFields["ТекстовоеПоле2"].Range.Text = wx.Cells[i, 2].Text; oDoc.FormFields["ТекстовоеПоле3"].Range.Text = wx.Cells[i, 8].Text; oDoc.FormFields["ТекстовоеПоле4"].Range.Text = wx.Cells[i, 13].Text; oDoc.FormFields["ТекстовоеПоле5"].Range.Text = wx.Cells[i, 12].Text; oDoc.FormFields["ТекстовоеПоле6"].Range.Text = wx.Cells[i, 13].Text; oRange.Copy(); par.Range.Paste(); unit = Word.WdUnits.wdStory; extend = Word.WdMovementType.wdMove; word.Selection.EndKey(ref unit, ref extend); oType = Word.WdBreakType.wdSectionBreakNextPage; word.Selection.InsertBreak(ref oType); oRng = wordFile.Bookmarks.get_Item(ref oEndofDoc).Range; par = wordFile.Content.Paragraphs.Add(ref oRng); oDoc.Close(false, Type.Missing, Type.Missing); } word.Visible = true; //SaveAsFile(wordFile); //wordFile.Close(); wbv.Close(false, Type.Missing, Type.Missing); excel.Quit(); //word.Quit(); } else { MessageBox.Show("Выберитие файл шаблона и файл с данными"); } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private void TableReport() { var dbTable = TablesClass.TableDisplay[TablesClass.SelectedTable]; var dialogResult = MessageBox.Show(@"Вы действительно хотите составить отчет по таблице " + dbTable, @"Отчет", MessageBoxButtons.YesNo); if (dialogResult != DialogResult.Yes) { return; } Word._Application application = new Word.Application(); Word._Document document = application.Documents.Add(); Word.Paragraph paragraph = document.Content.Paragraphs.Add(); application.Visible = true; paragraph.Range.Text = TablesClass.TableDisplay[TablesClass.SelectedTable]; paragraph.Range.Font.Bold = 16; paragraph.Range.Font.Size = 14; paragraph.Range.Font.Name = "Times New Roman"; paragraph.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; paragraph.Range.InsertParagraphAfter(); paragraph.Range.Font.Bold = 0; paragraph.Range.Font.Size = 12; paragraph.Range.Font.Name = "Times New Roman"; paragraph.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft; List <List <string> > list; if (TablesClass.SelectedTable == Tables.ORDERS.Name()) { list = TablesClass.GetList(TablesClass.SelectedTable, new Dictionary <string, Dictionary <string, string> > { { Tables.CUSTOMERS.Name(), new Dictionary <string, string> { { CustomerFields.CUS_Fullname.Name(), CustomerFields.CUS_Code.Name() } } }, { Tables.PHOTOGRAPHERS.Name(), new Dictionary <string, string> { { PhotographersFileds.PHO_Fullname.Name(), PhotographersFileds.PHO_Code.Name() } } }, { Tables.SERVICES.Name(), new Dictionary <string, string> { { ServicesFileds.SER_Description.Name(), ServicesFileds.SER_Code.Name() } } } }); } else if (TablesClass.SelectedTable == Tables.ASSISTANCE.Name()) { list = TablesClass.GetList(TablesClass.SelectedTable, new Dictionary <string, Dictionary <string, string> > { { Tables.ASSISTANTS.Name(), new Dictionary <string, string> { { AssistantsFileds.ASS_Fullname.Name(), AssistantsFileds.ASS_Code.Name() } } }, { Tables.ORDERS.Name(), new Dictionary <string, string> { { OrdersFileds.ORD_Date.Name(), OrdersFileds.ORD_Code.Name() } } }, }); } else { list = TablesClass.GetList(TablesClass.SelectedTable); } var numCols = TablesClass.FieldsDisplay.Count(r => r.Key.Substring(0, 3) == TablesClass.SelectedTable.Substring(0, 3).ToUpper()); Word.Table table = document.Tables.Add(paragraph.Range, list.Count, numCols); table.Borders.InsideLineStyle = Word.WdLineStyle.wdLineStyleSingle; table.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle; for (int i = 0; i < list.Count; i++) { for (int j = 0; j < numCols; j++) { table.Cell(i + 1, j + 1).Range.Text = list[i][j]; } } }
public override void Close() { if (m_WordApp != null) { if(m_doc != null) m_doc.Close(ref oMissing, ref oMissing, ref oMissing); m_WordApp.Quit(ref oMissing, ref oMissing, ref oMissing); m_doc = null; m_WordApp = null; } KillWordProcess(new TimeSpan(0, _INVALID_WORDPROC_TIMEOUT_, 0)); }
private void btnHeZhong_Click(object sender, EventArgs e) { //取得要架设的舟桥的长度,判断是否输入正确 string meter = this.textBox1.Text.Trim().ToString(); double temp; bool isNum = true; try { temp = Convert.ToDouble(meter); } catch (System.Exception ex) { MessageBox.Show("输入错误,请重新输入"); isNum = false; return; } if (isNum) { temp = Convert.ToDouble(meter); if (temp < 101.26 || temp > 1000) { MessageBox.Show("输入错误:河中部分最小宽度为101.26米,最大为1000米"); this.textBox1.Text = null; return; } } //根据输入的米数,计算需要架设多少米的桥 //这里有两个数字,门桥数量和边孔数量 //门桥长度=16.2,边孔长度=34.28,门桥数量需要计算,边孔数量则固定为2个 //粗略计算出来的门桥长度 = (要架设的桥长度-边孔长度/2)/门桥长度,这里只需要取整数部分即可 double lengthOfmenqiao = 16.2; //门桥长度 double lengthOfbiankong = 34.28; //边孔长度 int numOfbiankong = 2; //边孔数量固定,不需要变 double doubleOfmenqiao = (Convert.ToDouble(meter) - 2 * lengthOfbiankong) / lengthOfmenqiao; //int numOfmenqiao = Convert.ToInt16(doubleOfmenqiao);//这里只需要取整,得到门桥数量 int numOfmenqiao = Convert.ToInt16(Math.Truncate(doubleOfmenqiao)); double numofbeiyong = 1.2; int K = 1; Word._Application appCreate;// = new Word.ApplicationClass();//= new Word.Application(); Word._Document doc = null; appCreate = new Word.Application(); object missing = System.Reflection.Missing.Value; object readOnly = false; object isVisable = false; object index = 1; File.Copy(Application.StartupPath + "\\PrimData\\铁路舟桥河中部分器材数量表模板.doc", Application.StartupPath + "\\PrimData\\temp.doc", true); object FileName = Application.StartupPath + "\\PrimData\\temp.doc"; string finalFileName; try { this.textBox1.Enabled = false; this.btnHeZhong.Enabled = false; doc = appCreate.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 isVisable, ref missing, ref missing, ref missing, ref missing); //在文档的首行写入门桥数量,边孔数量,以及架设桥的长度 string strTextOfFirstLine = "舟桥总长度为: " + (numOfmenqiao * lengthOfmenqiao + numOfbiankong * lengthOfbiankong).ToString() + "米" + "\r\n"; string strTextOfSecondtLine = "门桥数量为: " + numOfmenqiao.ToString() + " " + "边孔数量:" + numOfbiankong.ToString() + "\r\n"; doc.Paragraphs[1].Range.Select(); doc.Paragraphs[1].Range.Text = strTextOfFirstLine; doc.Paragraphs[2].Range.Select(); doc.Paragraphs[2].Range.Text = strTextOfSecondtLine; //string teststr = doc.Paragraphs[1].Range.Text.ToString(); //object bookMarksIndex = 1; //doc.Bookmarks.get_Item(ref bookMarksIndex).Range.Text= strTextOfFirstLine; //bookMarksIndex = 2; //doc.Bookmarks.get_Item(ref bookMarksIndex).Range.Text = strTextOfSecondtLine; //doc.Paragraphs[1].Range.Text = strTextOfFirstLine.ToString(); // MessageBox.Show(doc.Tables.Count.ToString()); 统计word内的表格数o //获取第一个表格,并修改其相应内容 Word.Table tempTable = doc.Tables[1]; //填充第一个表的表头,舟桥长度, 2行6列 tempTable.Cell(2, 6).Range.Text = meter.ToString(); #region //填充第一张表的其他部分,第一张表只需要填充下表头即可,数据不用修改,注释掉先 //填充第一个表的3-14行 //for (int i = 3; i <= 14; i++) //{ // string tableContent = tempTable.Cell(i, 6).Range.Text.Trim().ToString(); // tableContent = tableContent.Remove(tableContent.Length - 2, 2); // int num = Convert.ToInt16(tableContent) * K; // tempTable.Cell(i, 6).Range.Text = num.ToString(); //} #endregion int numBeforeBracket, numInBracket; #region //获取第二个表格,只需要填充第9列,把7,8列的对应相乘即可 tempTable = doc.Tables[2]; //填充第二个表的舟桥长度, 1行7列 tempTable.Cell(1, 7).Range.Text = "架设" + meter.ToString() + "米舟桥数量"; //单独处理10行7列和26行7列的小数,再相加 for (int i = 3; i <= 34; i++) { if (i == 10 || i == 26) //过滤掉第10列和第26列 { i = i + 1; string rowTen = tempTable.Cell(10, 7).Range.Text.ToString(); rowTen = rowTen.Remove(rowTen.Length - 2, 2); tempTable.Cell(10, 9).Range.Text = (Convert.ToDouble(rowTen) * numOfmenqiao).ToString(); rowTen = tempTable.Cell(26, 7).Range.Text.ToString(); rowTen = rowTen.Remove(rowTen.Length - 2, 2); tempTable.Cell(26, 9).Range.Text = (Convert.ToDouble(rowTen) * numOfmenqiao + Convert.ToInt16(tempTable.Cell(26, 8).Range.Text.ToString().Remove(tempTable.Cell(26, 8).Range.Text.ToString().Length - 2, 2))).ToString(); } string tableContent = tempTable.Cell(i, 9).Range.Text.Trim().ToString(); if (tableContent.Length < 2) { tempTable.Cell(i, 9).Range.Text = null; } else if (tableContent.Length >= 8) { string rowOfSvStr = null; if (tempTable.Cell(i, 7).Range.Text.Trim().ToString().Length > 2) { rowOfSvStr = tempTable.Cell(i, 7).Range.Text.Trim().ToString().Remove(tempTable.Cell(i, 7).Range.Text.Trim().ToString().Length - 2, 2); } else { rowOfSvStr = null; } string rowOfEIStr = null; if (tempTable.Cell(i, 8).Range.Text.Trim().ToString().Length > 2) { rowOfEIStr = tempTable.Cell(i, 8).Range.Text.Trim().ToString().Remove(tempTable.Cell(i, 8).Range.Text.Trim().ToString().Length - 2, 2); } else { rowOfEIStr = null; } int rowIofSV = Convert.ToInt16(rowOfSvStr) * numOfmenqiao; //处理第7列的门桥数量 int rowIofEI = Convert.ToInt16(rowOfEIStr) * numOfbiankong; //处理第8列的边孔数量 tempTable.Cell(i, 9).Range.Text = (rowIofSV + rowIofEI).ToString() + "\n" + "(" + (Convert.ToInt16((rowIofSV + rowIofEI) * numofbeiyong)).ToString() + ")"; } else { string rowOfSvStr = null; if (tempTable.Cell(i, 7).Range.Text.Trim().ToString().Length > 2) { rowOfSvStr = tempTable.Cell(i, 7).Range.Text.Trim().ToString().Remove(tempTable.Cell(i, 7).Range.Text.Trim().ToString().Length - 2, 2); } else { rowOfSvStr = null; } string rowOfEIStr = null; if (tempTable.Cell(i, 8).Range.Text.Trim().ToString().Length > 2) { rowOfEIStr = tempTable.Cell(i, 8).Range.Text.Trim().ToString().Remove(tempTable.Cell(i, 8).Range.Text.Trim().ToString().Length - 2, 2); } else { rowOfEIStr = null; } int rowIofSV = Convert.ToInt16(rowOfSvStr) * numOfmenqiao; //处理第7列的门桥数量 int rowIofEI = Convert.ToInt16(rowOfEIStr) * numOfbiankong; //处理第8列的边孔数量 // tableContent = tableContent.Remove(tableContent.Length - 2, 2); // int num = Convert.ToInt16(tableContent) * K; tempTable.Cell(i, 9).Range.Text = (rowIofSV + rowIofEI).ToString(); } } //单独处理10行7列和26行7列的小数 #endregion //第二个表格处理完毕 #region //处理第三个表格 tempTable = doc.Tables[3]; //表头 tempTable.Cell(1, 7).Range.Text = "架设" + meter.ToString() + "米舟桥数量"; //处理表格数据 for (int i = 3; i <= 11; i++) { if (i == 10 || i == 26) //过滤掉第10列和第26列 { i = i + 1; } string tableContent = tempTable.Cell(i, 9).Range.Text.Trim().ToString(); if (tableContent.Length < 2) { tempTable.Cell(i, 9).Range.Text = null; } else if (tableContent.Length >= 8) { string rowOfSvStr = null; if (tempTable.Cell(i, 7).Range.Text.Trim().ToString().Length > 2) { rowOfSvStr = tempTable.Cell(i, 7).Range.Text.Trim().ToString().Remove(tempTable.Cell(i, 7).Range.Text.Trim().ToString().Length - 2, 2); } else { rowOfSvStr = null; } string rowOfEIStr = null; if (tempTable.Cell(i, 8).Range.Text.Trim().ToString().Length > 2) { rowOfEIStr = tempTable.Cell(i, 8).Range.Text.Trim().ToString().Remove(tempTable.Cell(i, 8).Range.Text.Trim().ToString().Length - 2, 2); } else { rowOfEIStr = null; } int rowIofSV = Convert.ToInt16(rowOfSvStr) * numOfmenqiao; //处理第7列的门桥数量 int rowIofEI = Convert.ToInt16(rowOfEIStr) * numOfbiankong; //处理第8列的边孔数量 tempTable.Cell(i, 9).Range.Text = (rowIofSV + rowIofEI).ToString() + "\n" + "(" + (Convert.ToInt16((rowIofSV + rowIofEI) * numofbeiyong)).ToString() + ")"; } else { string rowOfSvStr = null; if (tempTable.Cell(i, 7).Range.Text.Trim().ToString().Length > 2) { rowOfSvStr = tempTable.Cell(i, 7).Range.Text.Trim().ToString().Remove(tempTable.Cell(i, 7).Range.Text.Trim().ToString().Length - 2, 2); } else { rowOfSvStr = null; } string rowOfEIStr = null; if (tempTable.Cell(i, 8).Range.Text.Trim().ToString().Length > 2) { rowOfEIStr = tempTable.Cell(i, 8).Range.Text.Trim().ToString().Remove(tempTable.Cell(i, 8).Range.Text.Trim().ToString().Length - 2, 2); } else { rowOfEIStr = null; } int rowIofSV = Convert.ToInt16(rowOfSvStr) * numOfmenqiao; //处理第7列的门桥数量 int rowIofEI = Convert.ToInt16(rowOfEIStr) * numOfbiankong; //处理第8列的边孔数量 // tableContent = tableContent.Remove(tableContent.Length - 2, 2); // int num = Convert.ToInt16(tableContent) * K; tempTable.Cell(i, 9).Range.Text = (rowIofSV + rowIofEI).ToString(); } } #endregion //第三个表格无特殊情况,处理完毕 #region //处理第四个表格 tempTable = doc.Tables[4]; //表头 tempTable.Cell(1, 7).Range.Text = "架设" + meter.ToString() + "米舟桥数量"; //处理表格数据,4-26行 ,16行单独处理 for (int i = 4; i <= 26; i++) { if (i == 16) { i = i + 1; //16行有括号,在这里单独处理第16行 string tempstrSixteen = tempTable.Cell(16, 7).Range.Text.ToString(); //.Remove(tempTable.Cell(16,7).Range.Text.ToString().Length-2,2);//16行7列 numBeforeBracket = getNumBeforeBracketNoR(tempstrSixteen); //每门桥 tempstrSixteen = tempTable.Cell(16, 8).Range.Text.ToString().Remove(tempTable.Cell(16, 8).Range.Text.ToString().Length - 2, 2); //16行7列 int tempSixteenEightC = Convert.ToInt16(tempstrSixteen); //16行8列,每边孔 tempTable.Cell(16, 9).Range.Text = (numBeforeBracket * numOfmenqiao + tempSixteenEightC * numOfbiankong).ToString(); } //有些行不是9列,跳过 if (i == 19 || i == 23) { i = i + 1; } string tableContent = tempTable.Cell(i, 9).Range.Text.Trim().ToString(); if (tableContent.Length < 2) { tempTable.Cell(i, 9).Range.Text = null; } else if (tableContent.Length >= 8) { string rowOfSvStr = null; if (tempTable.Cell(i, 7).Range.Text.Trim().ToString().Length > 2) { rowOfSvStr = tempTable.Cell(i, 7).Range.Text.Trim().ToString().Remove(tempTable.Cell(i, 7).Range.Text.Trim().ToString().Length - 2, 2); } else { rowOfSvStr = null; } string rowOfEIStr = null; if (tempTable.Cell(i, 8).Range.Text.Trim().ToString().Length > 2) { rowOfEIStr = tempTable.Cell(i, 8).Range.Text.Trim().ToString().Remove(tempTable.Cell(i, 8).Range.Text.Trim().ToString().Length - 2, 2); } else { rowOfEIStr = null; } int rowIofSV = Convert.ToInt16(rowOfSvStr) * numOfmenqiao; //处理第7列的门桥数量 int rowIofEI = Convert.ToInt16(rowOfEIStr) * numOfbiankong; //处理第8列的边孔数量 tempTable.Cell(i, 9).Range.Text = (rowIofSV + rowIofEI).ToString() + "\n" + "(" + (Convert.ToInt16((rowIofSV + rowIofEI) * numofbeiyong)).ToString() + ")"; } else { string rowOfSvStr = null; if (tempTable.Cell(i, 7).Range.Text.Trim().ToString().Length > 2) { rowOfSvStr = tempTable.Cell(i, 7).Range.Text.Trim().ToString().Remove(tempTable.Cell(i, 7).Range.Text.Trim().ToString().Length - 2, 2); } else { rowOfSvStr = null; } string rowOfEIStr = null; if (tempTable.Cell(i, 8).Range.Text.Trim().ToString().Length > 2) { rowOfEIStr = tempTable.Cell(i, 8).Range.Text.Trim().ToString().Remove(tempTable.Cell(i, 8).Range.Text.Trim().ToString().Length - 2, 2); } else { rowOfEIStr = null; } int rowIofSV = Convert.ToInt16(rowOfSvStr) * numOfmenqiao; //处理第7列的门桥数量 int rowIofEI = Convert.ToInt16(rowOfEIStr) * numOfbiankong; //处理第8列的边孔数量 // tableContent = tableContent.Remove(tableContent.Length - 2, 2); // int num = Convert.ToInt16(tableContent) * K; tempTable.Cell(i, 9).Range.Text = (rowIofSV + rowIofEI).ToString(); } } #endregion //第四个表格处理完毕 #region //处理第五个表格,无特殊情况,直接处理 tempTable = doc.Tables[5]; //表头 tempTable.Cell(1, 7).Range.Text = "架设" + meter.ToString() + "米舟桥数量"; //处理表格数据,4-25行 for (int i = 4; i <= 25; i++) { //第10行不需要填充,,跳过 if (i == 10) { i = i + 1; } string tableContent = tempTable.Cell(i, 9).Range.Text.Trim().ToString(); if (tableContent.Length < 2) { tempTable.Cell(i, 9).Range.Text = null; } else if (tableContent.Length >= 8) { string rowOfSvStr = null; if (tempTable.Cell(i, 7).Range.Text.Trim().ToString().Length > 2) { rowOfSvStr = tempTable.Cell(i, 7).Range.Text.Trim().ToString().Remove(tempTable.Cell(i, 7).Range.Text.Trim().ToString().Length - 2, 2); } else { rowOfSvStr = null; } string rowOfEIStr = null; if (tempTable.Cell(i, 8).Range.Text.Trim().ToString().Length > 2) { rowOfEIStr = tempTable.Cell(i, 8).Range.Text.Trim().ToString().Remove(tempTable.Cell(i, 8).Range.Text.Trim().ToString().Length - 2, 2); } else { rowOfEIStr = null; } int rowIofSV = Convert.ToInt16(rowOfSvStr) * numOfmenqiao; //处理第7列的门桥数量 int rowIofEI = Convert.ToInt16(rowOfEIStr) * numOfbiankong; //处理第8列的边孔数量 tempTable.Cell(i, 9).Range.Text = (rowIofSV + rowIofEI).ToString() + "\n" + "(" + (Convert.ToInt16((rowIofSV + rowIofEI) * numofbeiyong)).ToString() + ")"; } else { string rowOfSvStr = null; if (tempTable.Cell(i, 7).Range.Text.Trim().ToString().Length > 2) { rowOfSvStr = tempTable.Cell(i, 7).Range.Text.Trim().ToString().Remove(tempTable.Cell(i, 7).Range.Text.Trim().ToString().Length - 2, 2); } else { rowOfSvStr = null; } string rowOfEIStr = null; if (tempTable.Cell(i, 8).Range.Text.Trim().ToString().Length > 2) { rowOfEIStr = tempTable.Cell(i, 8).Range.Text.Trim().ToString().Remove(tempTable.Cell(i, 8).Range.Text.Trim().ToString().Length - 2, 2); } else { rowOfEIStr = null; } int rowIofSV = Convert.ToInt16(rowOfSvStr) * numOfmenqiao; //处理第7列的门桥数量 int rowIofEI = Convert.ToInt16(rowOfEIStr) * numOfbiankong; //处理第8列的边孔数量 // tableContent = tableContent.Remove(tableContent.Length - 2, 2); // int num = Convert.ToInt16(tableContent) * K; tempTable.Cell(i, 9).Range.Text = (rowIofSV + rowIofEI).ToString(); } } #endregion //第五个表格处理完毕 #region //处理第六个表格 tempTable = doc.Tables[6]; //处理表格数据,3-12行,第9行特殊,单独处理 for (int i = 3; i <= 12; i++) { if (i == 9) { i = i + 1; //单独处理第六个表格的第9行 string sixTableNineRowS = tempTable.Cell(9, 7).Range.Text.ToString(); //获得第七列的字符串 string sixTableNineRowENum = (getNumBeforeBracket(sixTableNineRowS) * numOfbiankong).ToString(); //计算出第八列的结果 tempTable.Cell(9, 8).Range.Text = sixTableNineRowENum + "\r" + sixTableNineRowENum + "\r" + sixTableNineRowENum + "\r"; } string tableContent = tempTable.Cell(i, 8).Range.Text.Trim().ToString(); if (tableContent.Length < 2) { tempTable.Cell(i, 8).Range.Text = null; } else if (tableContent.Length >= 8) { string rowOfSvStr = tempTable.Cell(i, 7).Range.Text.Trim().ToString().Remove(tempTable.Cell(i, 7).Range.Text.Trim().ToString().Length - 2, 2); int rowIofSV = Convert.ToInt16(rowOfSvStr) * numOfmenqiao; //处理第7列的门桥数量 tempTable.Cell(i, 8).Range.Text = (rowIofSV * numOfbiankong).ToString() + "\n" + "(" + (Convert.ToInt16((rowIofSV * numOfbiankong) * numofbeiyong)).ToString() + ")"; } else { string rowOfSvStr = tempTable.Cell(i, 7).Range.Text.Trim().ToString().Remove(tempTable.Cell(i, 7).Range.Text.Trim().ToString().Length - 2, 2); int rowIofSV = Convert.ToInt16(rowOfSvStr) * numOfmenqiao; //处理第7列的门桥数量 // tableContent = tableContent.Remove(tableContent.Length - 2, 2); // int num = Convert.ToInt16(tableContent) * K; tempTable.Cell(i, 8).Range.Text = (rowIofSV * numOfbiankong).ToString(); } } #endregion //第六个表格处理完毕 #region //处理第7个表格 //获取第七个表格 tempTable = doc.Tables[7]; //处理表头 tempTable.Cell(1, 6).Range.Text = "架设" + meter.ToString() + "米舟桥数量"; //3-32行 //单独处理18,19,21,23,24 for (int i = 3; i <= 32; i++) { //先处理18,19,21,23,24行 if (i == 18 || i == 19 || i == 21 || i == 23 || i == 24) { string rowstrSix = tempTable.Cell(i, 6).Range.Text.ToString(); double rowNumSix = Convert.ToDouble(rowstrSix.Remove(rowstrSix.Length - 2, 2)); string rowstrSeven = tempTable.Cell(i, 7).Range.Text.ToString(); int rowNumSeven = Convert.ToInt16(rowstrSeven.Remove(rowstrSeven.Length - 2, 2)); tempTable.Cell(i, 8).Range.Text = (rowNumSix * numOfmenqiao + rowNumSeven * numOfbiankong).ToString(); } if (i == 18 || i == 21 || i == 23) { i = i + 1; //18行 } if (i == 19 || i == 24) { i = i + 1; } string tableContent = tempTable.Cell(i, 8).Range.Text.Trim().ToString(); if (tableContent.Length < 2) { tempTable.Cell(i, 8).Range.Text = null; } else if (tableContent.Length >= 8) { string rowOfSixStr = null; if (tempTable.Cell(i, 6).Range.Text.Trim().ToString().Length > 2) { rowOfSixStr = tempTable.Cell(i, 6).Range.Text.Trim().ToString().Remove(tempTable.Cell(i, 6).Range.Text.Trim().ToString().Length - 2, 2); } else { rowOfSixStr = null; } string rowOfSvStr = null; if (tempTable.Cell(i, 7).Range.Text.Trim().ToString().Length > 2) { rowOfSvStr = tempTable.Cell(i, 7).Range.Text.Trim().ToString().Remove(tempTable.Cell(i, 7).Range.Text.Trim().ToString().Length - 2, 2); } else { rowOfSvStr = null; } int rowIofSix = Convert.ToInt16(rowOfSixStr) * numOfmenqiao; //处理第6列的门桥数量 int rowIofSv = Convert.ToInt16(rowOfSvStr) * numOfbiankong; //处理第7列的边孔数量 tempTable.Cell(i, 8).Range.Text = (rowIofSix + rowIofSv).ToString() + "\n" + "(" + (Convert.ToInt16((rowIofSix + rowIofSv) * numofbeiyong)).ToString() + ")"; } else { string rowOfSixStr = null; if (tempTable.Cell(i, 6).Range.Text.Trim().ToString().Length > 2) { rowOfSixStr = tempTable.Cell(i, 6).Range.Text.Trim().ToString().Remove(tempTable.Cell(i, 6).Range.Text.Trim().ToString().Length - 2, 2); } else { rowOfSixStr = null; } string rowOfSvStr = null; if (tempTable.Cell(i, 7).Range.Text.Trim().ToString().Length > 2) { rowOfSvStr = tempTable.Cell(i, 7).Range.Text.Trim().ToString().Remove(tempTable.Cell(i, 7).Range.Text.Trim().ToString().Length - 2, 2); } else { rowOfSvStr = null; } int rowIofSix = Convert.ToInt16(rowOfSixStr) * numOfmenqiao; //处理第6列的门桥数量 int rowIofSv = Convert.ToInt16(rowOfSvStr) * numOfbiankong; //处理第7列的边孔数量 // tableContent = tableContent.Remove(tableContent.Length - 2, 2); // int num = Convert.ToInt16(tableContent) * K; tempTable.Cell(i, 8).Range.Text = (rowIofSix + rowIofSv).ToString(); } } #endregion //第七张表处理结束 doc.Save(); this.textBox1.Enabled = true; this.btnHeZhong.Enabled = true; finalFileName = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + meter.ToString() + "米铁路舟桥河中部分器材数量表.doc"; File.Copy(Application.StartupPath + "\\PrimData\\temp.doc", finalFileName, true); MessageBox.Show(meter.ToString() + "米铁路舟桥河中部分器材数量表生成成功,已保存至桌面"); } catch (Exception ex) { MessageBox.Show(ex.ToString()); return; } finally { if (doc != null) { doc.Close(ref missing, ref missing, ref missing); doc = null; } if (appCreate != null) { appCreate.Quit(ref missing, ref missing, ref missing); appCreate = null; } } }
/// <summary> /// 保存word文档 /// </summary> public void SaveWord() { object missing = System.Reflection.Missing.Value; Object Nothing = System.Reflection.Missing.Value; object Visible = false; try { object Save_FileName = _SaveFilePath; _MainDoc.SaveAs(ref Save_FileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref Visible, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); _MainDoc.Close(ref Nothing, ref Nothing, ref Nothing); _MainDoc = null; _WordApplicMain.Quit(ref Nothing, ref Nothing, ref Nothing); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }
//将word文档转换成PDF格式 private bool FConvertWORD(string sourcePath, string targetPath //, Word.WdExportFormat exportFormat ) { Word.WdExportFormat exportFormat = Word.WdExportFormat.wdExportFormatPDF; bool result; object paramMissing = Type.Missing; Word.ApplicationClass wordApplication = new Word.ApplicationClass(); Word._Document wordDocument = null; try { object paramSourceDocPath = sourcePath; string paramExportFilePath = targetPath; Word.WdExportFormat paramExportFormat = exportFormat; bool paramOpenAfterExport = false; Word.WdExportOptimizeFor paramExportOptimizeFor = Word.WdExportOptimizeFor.wdExportOptimizeForPrint; Word.WdExportRange paramExportRange = Word.WdExportRange.wdExportAllDocument; int paramStartPage = 0; int paramEndPage = 0; Word.WdExportItem paramExportItem = Word.WdExportItem.wdExportDocumentContent; bool paramIncludeDocProps = true; bool paramKeepIRM = true; Word.WdExportCreateBookmarks paramCreateBookmarks = Word.WdExportCreateBookmarks.wdExportCreateWordBookmarks; bool paramDocStructureTags = true; bool paramBitmapMissingFonts = true; bool paramUseISO19005_1 = false; wordDocument = wordApplication.Documents.Open( ref paramSourceDocPath, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing); if (wordDocument != null) { wordDocument.ExportAsFixedFormat(paramExportFilePath, paramExportFormat, paramOpenAfterExport, paramExportOptimizeFor, paramExportRange, paramStartPage, paramEndPage, paramExportItem, paramIncludeDocProps, paramKeepIRM, paramCreateBookmarks, paramDocStructureTags, paramBitmapMissingFonts, paramUseISO19005_1, ref paramMissing); } result = true; } finally { if (wordDocument != null) { wordDocument.Close(ref paramMissing, ref paramMissing, ref paramMissing); wordDocument = null; } if (wordApplication != null) { wordApplication.Quit(ref paramMissing, ref paramMissing, ref paramMissing); wordApplication = null; } System.GC.Collect(); System.GC.WaitForPendingFinalizers(); System.GC.Collect(); System.GC.WaitForPendingFinalizers(); } return(result); }
public void MakeReport(DataGridView WorkerGrid, DataGridView WorkGrid, DataGridView InstructionGrid) { string[,] Worker = SaveDataFromDGV(WorkerGrid); // инициализация двумерного массива для работы string[,] Instruction = SaveInstructionAndWorkFromDGV(InstructionGrid); application = new Word.Application(); // инициализация ворд документа object templatePathObj = Application.StartupPath + @"\Template.docx"; // путь до документа try { document = application.Documents.Add(ref templatePathObj, ref missingObj, ref missingObj, ref missingObj); // открытие документа } catch (Exception error) // в случае ошибки подчищаем память и показываем ошибку. { document.Close(ref falseObj, ref missingObj, ref missingObj); application.Quit(ref missingObj, ref missingObj, ref missingObj); document = null; application = null; //throw error; MessageBox.Show(error.ToString(), "OK", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1); } string workStart = "08:00"; string workEnd = "17:00"; //application.Visible = true; object bookmarkObj = "Naryad_Number"; // здесь и ниже заполняем текст в документе. Word.Range bookmarkRange = document.Bookmarks.get_Item(ref bookmarkObj).Range; bookmarkRange.Text = form.naryadNomer.Text; bookmarkObj = "Naryad_Date"; bookmarkRange = document.Bookmarks.get_Item(ref bookmarkObj).Range; bookmarkRange.Text = form.Date.Text; bookmarkObj = "Workman"; bookmarkRange = document.Bookmarks.get_Item(ref bookmarkObj).Range; bookmarkRange.Text = form.workman.Text; bookmarkObj = "AmountWorkers"; bookmarkRange = document.Bookmarks.get_Item(ref bookmarkObj).Range; bookmarkRange.Text = WorkerGrid.SelectedRows.Count.ToString(); bookmarkObj = "WorkStart"; bookmarkRange = document.Bookmarks.get_Item(ref bookmarkObj).Range; bookmarkRange.Text = workStart; bookmarkObj = "Date"; bookmarkRange = document.Bookmarks.get_Item(ref bookmarkObj).Range; bookmarkRange.Text = form.Date.Text; bookmarkObj = "WorkEnd"; bookmarkRange = document.Bookmarks.get_Item(ref bookmarkObj).Range; bookmarkRange.Text = workEnd; bookmarkObj = "Date2"; bookmarkRange = document.Bookmarks.get_Item(ref bookmarkObj).Range; bookmarkRange.Text = form.Date.Text; bookmarkObj = "Head"; bookmarkRange = document.Bookmarks.get_Item(ref bookmarkObj).Range; bookmarkRange.Text = form.head.Text; bookmarkObj = "Date3"; bookmarkRange = document.Bookmarks.get_Item(ref bookmarkObj).Range; bookmarkRange.Text = form.Date.Text; Print("WhatWork", WorkGrid); Print("Instruction", InstructionGrid); Print("InstructionID", InstructionGrid); bookmarkObj = "AmountWorkers2"; bookmarkRange = document.Bookmarks.get_Item(ref bookmarkObj).Range; bookmarkRange.Text = WorkerGrid.SelectedRows.Count.ToString(); Word.Table _table = document.Tables[1]; Word.Range _currentRange; for (int i = 0; i < WorkerGrid.SelectedRows.Count; i++) // в этом циеле заполняется таблица { _currentRange = _table.Cell(i + 2, 2).Range; _currentRange.Text = Worker[i, 0]; _currentRange = _table.Cell(i + 2, 3).Range; _currentRange.Text = Worker[i, 1]; } //печать и закрытие документа document.PrintOut(ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj); document.Close(Word.WdSaveOptions.wdDoNotSaveChanges); application.Quit(); }
/// <summary> /// 打开待打印WORD模板文件,以开始打印处理 /// </summary> /// <returns>打开成功则返回TRUE,否则返回FALSE</returns> public override bool Open() { object template = this.Template; object ReadOnly = false; object revert = true; object SavePath = this.SavePath; if (this.Available(this.Template)) { if (!ChkExtOfDocx()) return false; int TryCount = 0; while (true) { if (TryCopy(this.Template, this.SavePath)) { break; } else { Thread.Sleep(500); TryCount++; if (TryCount > _TRY_COUNT_) { return false; } } } //Monitor.Enter(template); //try { // File.Copy(this.Template, this.SavePath, true); //} //catch { // Thread.Sleep(200); // try // { // File.Copy(this.Template, this.SavePath, true); // } // catch { return false; } //} //Monitor.Exit(template); if (!File.Exists(this.SavePath)) return false; m_doc = m_WordApp.Documents.Open(ref SavePath, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref revert, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); m_doc.Activate(); //m_doc.ActiveWindow.Document.Activate(); if (m_doc.Revisions.Count > 0) { m_doc.ShowRevisions = true; m_doc.TrackRevisions = true; m_doc.Revisions.AcceptAll(); } m_arKeyPosition = new ArrayList[m_doc.Tables.Count]; for (int iCount = 0; iCount < m_doc.Tables.Count; iCount++) { ArrayList alkp = TraverTable(iCount + 1); m_arKeyPosition.SetValue(alkp, iCount); } return true; } return false; }
public static void InitWordDoc() { if (null == app && null == doc) { app = new Word.Application(); app.Visible = false; // Setting these variables is comparable to passing null to the function. // This is necessary because the C# null cannot be passed by reference. object template = Missing.Value; object newTemplate = Missing.Value; object documentType = Missing.Value; object visible = true; doc = app.Documents.Add(ref template, ref newTemplate, ref documentType, ref visible); } else app.Visible = false; }
public ActionResult CreateDocumentsFromTemplate(ContractDetails details) { //Get data from db for current user DSGVOEntities1 db = new DSGVOEntities1(); kunden CurrentUser = db.kundens.Where(t => t.plz == details.UserZip.ToString().Trim() && t.seriennr.Substring(15).Trim() == details.SerialNo.ToString().Trim()).First(); ////Update contractuser in db //CurrentUser.contractuser = details.ContractUser.ToString().Trim(); ////Change email if it is changed //if (CurrentUser.email.ToString().Trim() != details.Email.ToString().Trim()) //{ // CurrentUser.email = details.Email.ToString().Trim(); //} //db.SaveChanges(); //Check if changes in data exist and send it in email StringBuilder dataChanges = new StringBuilder(); bool ChangesExist = false; dataChanges.Append("<table>"); dataChanges.Append(" <tr><th>Previous data</th><th>Changed data from user</th></tr>"); if (CurrentUser.name1.ToString().Trim() != details.Name1.ToString().Trim()) { ChangesExist = true; dataChanges.Append(" <tr><td>" + CurrentUser.name1.ToString().Trim() + " </td><td>" + details.Name1.ToString().Trim() + "</td></tr>"); CurrentUser.name1 = details.Name1.ToString().Trim(); } if (CurrentUser.name2.ToString().Trim() != details.Name2.ToString().Trim()) { ChangesExist = true; dataChanges.Append(" <tr><td>" + CurrentUser.name2.ToString().Trim() + " </td><td>" + details.Name2.ToString().Trim() + "</td></tr>"); CurrentUser.name2 = details.Name2.ToString().Trim(); } if (CurrentUser.strasse.ToString().Trim() != details.Street.ToString().Trim()) { ChangesExist = true; dataChanges.Append(" <tr><td>" + CurrentUser.strasse.ToString().Trim() + " </td><td>" + details.Street.ToString().Trim() + "</td></tr>"); CurrentUser.strasse = details.Street.ToString().Trim(); } if (CurrentUser.plz.ToString().Trim() != details.Zip.ToString().Trim()) { ChangesExist = true; dataChanges.Append(" <tr><td>" + CurrentUser.plz.ToString().Trim() + " </td><td>" + details.Zip.ToString().Trim() + "</td></tr>"); CurrentUser.plz = details.Zip.ToString().Trim(); } if (CurrentUser.ort.ToString().Trim() != details.City.ToString().Trim()) { ChangesExist = true; dataChanges.Append(" <tr><td>" + CurrentUser.ort.ToString().Trim() + " </td><td>" + details.City.ToString().Trim() + "</td></tr>"); CurrentUser.ort = details.City.ToString().Trim(); } //if (CurrentUser.land.ToString().Trim() != details.Country.ToString().Trim()) //{ // ChangesExist = true; // dataChanges.Append(" <tr><td>" + CurrentUser.land.ToString().Trim() + " </td><td>" + details.Country.ToString().Trim() + "</td></tr>"); //} if (CurrentUser.email.ToString().Trim() != details.Email.ToString().Trim()) { ChangesExist = true; dataChanges.Append(" <tr><td>" + CurrentUser.email.ToString().Trim() + " </td><td>" + details.Email.ToString().Trim() + "</td></tr>"); CurrentUser.email = details.Email.ToString().Trim(); } //if (CurrentUser.contractuser == null) //{ // ChangesExist = true; // dataChanges.Append(" <tr><td>Empty</td><td>" + details.ContractUser.ToString().Trim() + "</td></tr>"); //} ////Adding user data to viewbag //if (CurrentUser.name1 != null) //{ // details.Name1 = CurrentUser.name1.ToString().Trim(); //} //if (CurrentUser.name2 != null) //{ // details.Name2 = CurrentUser.name2.ToString().Trim(); //} //if (CurrentUser.strasse != null) //{ // details.Street= CurrentUser.strasse.ToString().Trim() + " " ; //} //if (CurrentUser.ort != null) //{ // details.City= CurrentUser.ort.ToString().Trim(); //} //if (CurrentUser.land != null) //{ // //Set country // switch (CurrentUser.land.ToString().Trim()) // { // case "D": // CurrentUser.land = "Deutschland"; // break; // case "A": // CurrentUser.land = "Österreich"; // break; // case "CH": // CurrentUser.land = "Schweiz"; // break; // default: // break; // } // details.Country = CurrentUser.land.ToString().Trim(); //} //if (CurrentUser.email != null) //{ // details.Contact = CurrentUser.email.ToString().Trim(); //} // Set country switch (details.Country.ToString().Trim()) { case "D": details.Country = "Deutschland"; break; case "A": details.Country = "Österreich"; break; case "CH": details.Country = "Schweiz"; break; default: break; } string Result, Name; //Generating strong name as word and pdf name string HashName = UserInfo.CalculateMD5Hash(details.SerialNo + "-" + details.UserZip); try { Spire.Doc.Document document = new Spire.Doc.Document(); document.LoadFromFile(Server.MapPath("~/Template/template.docx").ToString()); if (details.Name1 != null && details.Name1.ToString().Trim() != "") { document.Replace("##AGName1##", details.Name1, false, true); } else { document.Replace("##AGName1##", "", false, true); } if (details.Name2 != null && details.Name2.ToString().Trim() != "") { document.Replace("##AGName2##", details.Name2, false, true); } else { document.Replace("##AGName2##", "", false, true); } if (details.Street != null && details.Street.ToString().Trim() != "") { document.Replace("##AGStreet##", details.Street, false, true); } else { document.Replace("##AGStreet##", "", false, true); } if (details.Zip != null && details.Zip.ToString().Trim() != "") { document.Replace("##AGZIP##", details.Zip, false, true); } else { document.Replace("##AGZIP##", "", false, true); } if (details.City != null && details.City.ToString().Trim() != "") { document.Replace("##AGCITY##", details.City, false, true); document.Replace("##City##", details.City, false, true); } else { document.Replace("##AGCITY##", "", false, true); document.Replace("##City##", "", false, true); } if (details.Country != null && details.Country.ToString().Trim() != "") { document.Replace("##AGCountry##", details.Country, false, true); } else { document.Replace("##AGCountry##", "", false, true); } if (details.ContractUser != null && details.ContractUser.ToString().Trim() != "") { document.Replace("##ContractUser##", details.ContractUser, false, true); } if (details.Email != null && details.Email.ToString().Trim() != "") { document.Replace("##AGCONTACT##", details.Email, false, true); } else { document.Replace("##AGCONTACT##", "", false, true); } document.Replace("##DayDate##", DateTime.Now.ToString("dd.MM.yyyy"), false, true); document.SaveToFile(Server.MapPath("~/Word/").ToString() + HashName + ".docx", Spire.Doc.FileFormat.Docx); //Code for making connection with existing word template Microsoft.Office.Interop.Word._Application wApp = new Microsoft.Office.Interop.Word.Application(); Microsoft.Office.Interop.Word.Documents wDocs = wApp.Documents; Microsoft.Office.Interop.Word._Document wDoc = wDocs.Open(Server.MapPath("~/Word/").ToString() + HashName + ".docx", ReadOnly: false, Visible: false); wDoc.Activate(); string pdfName = @Server.MapPath("~/Pdf/").ToString() + HashName + ".pdf"; //wDoc.ExportAsFixedFormat(OutputFileName: pdfName, ExportFormat: WdExportFormat.wdExportFormatPDF, UseISO19005_1: true); wDoc.ExportAsFixedFormat( pdfName, WdExportFormat.wdExportFormatPDF, OptimizeFor: WdExportOptimizeFor.wdExportOptimizeForPrint, BitmapMissingFonts: true, DocStructureTags: false, UseISO19005_1: true); wDoc.Close(); //Update fields into db CurrentUser.contractuser = details.ContractUser; CurrentUser.contactperson = details.ContractUser; CurrentUser.contractsigned = true; CurrentUser.signeddate = DateTime.Now; CurrentUser.contractname = HashName + ".pdf"; //Send email with pdf as attachment to office SmtpClient smtpClient = new SmtpClient(); NetworkCredential basicCredential = new NetworkCredential("*****@*****.**", "hopeDSGVO"); System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(); MailAddress fromAddress = new MailAddress("*****@*****.**"); smtpClient.Host = "smtp.1und1.de"; smtpClient.UseDefaultCredentials = false; smtpClient.Credentials = basicCredential; smtpClient.Port = 587; smtpClient.EnableSsl = true; message.From = fromAddress; message.Subject = "hope-DSGVO - AV-Vertrag, Kunde: " + details.UserZip + " - hotel: " + details.Name1; message.Attachments.Add(new System.Net.Mail.Attachment(Server.MapPath("~/Pdf/").ToString() + HashName + ".pdf")); //[email protected] message.To.Add(new MailAddress("*****@*****.**")); smtpClient.Send(message); //Send email to customer SmtpClient smtpCustomer = new SmtpClient(); NetworkCredential basicCredentialCustomer = new NetworkCredential("*****@*****.**", "hopeDSGVO"); System.Net.Mail.MailMessage messageCustomer = new System.Net.Mail.MailMessage(); MailAddress fromAddressCompany = new MailAddress("*****@*****.**"); smtpCustomer.Host = "smtp.1und1.de"; smtpCustomer.UseDefaultCredentials = false; smtpCustomer.Credentials = basicCredential; smtpCustomer.Port = 587; smtpCustomer.EnableSsl = true; messageCustomer.From = fromAddressCompany; messageCustomer.Subject = "hope-DSGVO - AV-Vertrag, Kunde: " + details.UserZip + " - hotel: " + details.Name1; messageCustomer.Attachments.Add(new System.Net.Mail.Attachment(Server.MapPath("~/Pdf/").ToString() + HashName + ".pdf")); //[email protected] messageCustomer.To.Add(new MailAddress(CurrentUser.email.ToString().Trim())); smtpCustomer.Send(messageCustomer); //Send email if user changed data on html form [email protected] if (ChangesExist) { //Send email with pdf as attachemnt SmtpClient smtpClientSecond = new SmtpClient(); NetworkCredential basicCredentialSecond = new NetworkCredential("*****@*****.**", "hopeDSGVO"); System.Net.Mail.MailMessage messageSecond = new System.Net.Mail.MailMessage(); MailAddress fromAddressSecond = new MailAddress("*****@*****.**"); smtpClientSecond.Host = "smtp.1und1.de"; smtpClientSecond.UseDefaultCredentials = false; smtpClientSecond.Credentials = basicCredential; smtpClientSecond.Port = 587; smtpClientSecond.EnableSsl = true; messageSecond.From = fromAddress; messageSecond.Subject = "hope-DSGVO - Kundendaten geändert: " + details.UserZip + " - hotel: " + details.Name1; messageSecond.IsBodyHtml = true; messageSecond.Body = dataChanges.ToString(); //[email protected] messageSecond.To.Add(new MailAddress("*****@*****.**")); smtpClientSecond.Send(message); //Update field in database CurrentUser.datachanged = true; } //Update field in database db.SaveChanges(); return(Json(new { Result = "true", Name = HashName })); } catch (Exception ex) { Console.WriteLine("Error occured:", ex.ToString()); return(Json(Result = ex.ToString())); } finally { Dispose(); } }
static void Main(string[] args) { FileInfo file = new FileInfo(@args[0]); if (file.Extension.ToLower() == ".doc" || file.Extension.ToLower() == ".xml" || file.Extension.ToLower() == ".wml" || file.Extension.ToLower() == ".docx") { Console.WriteLine("Starting document conversion..."); //Set the Word Application Window Title string wordAppId = "" + DateTime.Now.Ticks; Word.Application word = new Word.Application(); word.Application.Caption = wordAppId; word.Application.Visible = true; int processId = GetProcessIdByWindowTitle(wordAppId); word.Application.Visible = false; try { object filename = file.FullName; string newfilename = Path.ChangeExtension(file.FullName, ".pdf"); Word._Document document = word.Documents.OpenNoRepairDialog(filename, ConfirmConversions: false, ReadOnly: true, AddToRecentFiles: false, PasswordDocument: Type.Missing, PasswordTemplate: Type.Missing, Revert: false, WritePasswordDocument: Type.Missing, WritePasswordTemplate: Type.Missing, Format: Type.Missing, Encoding: Type.Missing, Visible: false, OpenAndRepair: false, DocumentDirection: Type.Missing, NoEncodingDialog: true, XMLTransform: Type.Missing); Console.WriteLine("Converting document '{0}' to PDF.", file); document.ExportAsFixedFormat( newfilename, Word.WdExportFormat.wdExportFormatPDF, OpenAfterExport: false, OptimizeFor: Word.WdExportOptimizeFor.wdExportOptimizeForOnScreen, Range: Word.WdExportRange.wdExportAllDocument, Item: Word.WdExportItem.wdExportDocumentContent, IncludeDocProps: true, KeepIRM: false, CreateBookmarks: Word.WdExportCreateBookmarks.wdExportCreateHeadingBookmarks, DocStructureTags: true, BitmapMissingFonts: false, UseISO19005_1: false, FixedFormatExtClassPtr: Type.Missing); document.Close(); document = null; word.Quit(); word = null; Console.WriteLine("Success, quitting Word."); } catch (Exception e) { Console.WriteLine("Error ocurred: {0}", e); } finally { // Terminate Winword instance by PID. Console.WriteLine("Terminating Winword process with the Windowtitle '{0}' and the Application ID: '{1}'.", wordAppId, processId); try { Process process = Process.GetProcessById(processId); process.Kill(); } catch { Console.WriteLine("No Winword instance currently running with the give id '{0}', everything fine.", processId); } } } else { Console.WriteLine("Only DOC / WML / XML files possible."); } }
/// <summary> /// 创建word文档 /// </summary> public void CreateWord() { _WordApplicMain = new Microsoft.Office.Interop.Word.Application(); _MainDoc = _WordApplicMain.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing); SetPageDefaultStyle(new MyWordPageStyle()); }
private void button1_Click(object sender, RoutedEventArgs e) { OpenFileDialog openFileDialog1 = new OpenFileDialog(); openFileDialog1.Filter = "ZTree Pay Files (*.pay)|*.pay|All Files|*.*"; openFileDialog1.Multiselect = true; bool? userClickedOK = openFileDialog1.ShowDialog(); if (userClickedOK == true) { readPayFile(openFileDialog1.FileName); Microsoft.Office.Interop.Word.Selection wrdSelection; Microsoft.Office.Interop.Word.MailMerge wrdMailMerge; string StrToAdd; wrdApp = new Microsoft.Office.Interop.Word.Application(); wrdApp.Visible = true; wrdDoc = wrdApp.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); wrdDoc.Select(); wrdSelection = wrdApp.Selection; foreach (Participant partip in this.adat) { wrdSelection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight; wrdSelection.Font.Size = 26; wrdSelection.Font.Name = "Arial"; wrdSelection.TypeText("Receipt \r\n Seat number: " + partip.boothno); wrdSelection.Font.Size = 10; wrdSelection.Font.Name = "Times New Roman"; InsertLines(1); wrdSelection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft; StrToAdd = "\r\n COGNITION AND BEHAVIOR LAB"; try { string imgLocation = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "1.png"); wrdSelection.InlineShapes.AddPicture(imgLocation); } catch (Exception ex) { MessageBox.Show("Image file (1.png) not found!"); } wrdSelection.TypeText(StrToAdd); wrdSelection.TypeText("\r\nName: " + partip.name); wrdSelection.TypeText("\r\nCPR number: " + partip.cpr); wrdSelection.TypeText("\r\nYour earnings in today’s experiment: " + partip.profit + " kr. \r\n"); wrdSelection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphJustify; wrdSelection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphJustify; StrToAdd = "Aarhus University will automatically transfer the amount you earn into your NemKonto (for this we need your CPR number). This is simply your existing bank account, into which all payments from the public sector flow (e.g. tax refunds or SU student grants). Alexander Koch and his team will start registering the payments with the administration of Aarhus University this week. Then the administrative process might take between 2-6 weeks. You can contact Alexander Koch by email ([email protected]) if you want information on the payment process."; wrdSelection.TypeText(StrToAdd); wrdSelection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphJustify; InsertLines(1); StrToAdd = "According to Danish law, Aarhus University reports payments to the tax authorities. Please note that, depending on your personal income tax rate, taxes will be deducted from the amount of money you earn in this study. That is, the amount you will receive might be lower than the pre-tax earnings stated above."; wrdSelection.TypeText(StrToAdd); InsertLines(1); wrdSelection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight; Object objDate = "dddd, MMMM dd, yyyy"; wrdSelection.InsertDateTime(ref objDate, ref oFalse, ref oMissing, ref oMissing, ref oMissing); wrdSelection.InlineShapes.AddHorizontalLineStandard(); wrdSelection.InsertBreak(Microsoft.Office.Interop.Word.WdBreakType.wdPageBreak); } } }
public CopyEngine(string wordFile, string excelFile) { try { //OPEN NEW INSTANCE OF WORD Word._Application objWordApp = new Word.Application(); objWordApp.Visible = false; if (objWordApp == null) { Console.WriteLine("Word could not be started. Check that your office installation and project references are correct."); return; } Word._Document objDoc = objWordApp.Documents.Open(wordFile); //opens specified file in Word instance, stores it in objDoc if (objDoc.Tables.Count == 0) //quickfail if document has no tables { Console.WriteLine("This document contains no tables"); objWordApp.Quit(); //closes Word instance return; } //IF THE EXCEL FILE HAS ALREADY BEEN MADE, DELETES IT if (File.Exists(excelFile)) { File.Delete(excelFile); } //OPEN NEW INSTANCE OF EXCEL Excel._Application objExcelApp = new Excel.Application(); //creates instance of Excel objExcelApp.Visible = false; // false = headless true = visible UI Excel._Workbook workbook = objExcelApp.Workbooks.Add(1); //adds a single workbook Excel._Worksheet worksheet = (Excel.Worksheet)workbook.Sheets[1]; //creates a worksheet within the workbook if (worksheet == null) //if excel is acting wonky - bails { Console.WriteLine("Worksheet could not be created. Check that your office installation and project references are correct."); return; } else { Console.WriteLine("And here we go!\nCopy process has been started!"); } int excelRow = 1; //counter for excel rows (so the loops don't continuously overwrite the generated excel data) foreach (Word.Table table in objDoc.Tables) { string tableHeader = table.Cell(1, 1).Range.Text.Trim(); //grabs the table header and trims whitespace if (tableHeader.StartsWith("CEE")) //we're looking for the CEE tables - nothing else. { for (int row = 1; row <= table.Rows.Count; row++) { for (int col = 1; col <= table.Columns.Count; col++) { try { worksheet.Cells[excelRow, col] = objExcelApp.WorksheetFunction.Clean(table.Cell(row, col).Range.Text); } catch (Exception) { continue; // if an exception is thrown, 99% of the time it's due to merged cells in the word table. } } excelRow++; } } } // Save the excel file workbook.SaveAs(excelFile, Excel.XlFileFormat.xlWorkbookDefault); objExcelApp.Workbooks.Close(); objExcelApp.Application.Quit(); //Close the Word document objWordApp.Documents.Close(); objWordApp.Quit(); Console.WriteLine("\nWord document table contents copied to excel file: " + excelFile); Console.WriteLine("\nPress ANY Key To Start Conversion"); Console.ReadLine(); } catch (Exception ex) { //Console.WriteLine(ex); } }
void buildReport(ReportData[] data) { object oMissing = System.Reflection.Missing.Value; object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */ //Start Word and create a new document. Word._Application oWord = new Word.Application(); Word._Document oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); //oDoc.tit = "Gorodetskiy_Interpolation_Report.docx"; try { data.Where(d => d.MethodsData != null).ToList().ForEach(fucData => { // Insert title Word.Paragraph oPara; object oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oPara = oDoc.Content.Paragraphs.Add(ref oRng); oPara.Range.Text = $"Интерполяция для Y = {fucData.TestFunction.Name}"; oPara.Range.Bold = 1; oPara.Range.Font.Size = 18; oPara.Range.InsertParagraphAfter(); // Insert Interval oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oPara = oDoc.Content.Paragraphs.Add(ref oRng); oPara.Range.Text = $"X є [{fucData.TestFunction.XMin};{fucData.TestFunction.XMax}]. К-во точек = {fucData.MethodsData[0].Method.InputPoints.Count}"; oPara.Range.Bold = 0; oPara.Range.Font.Size = 14; oPara.Range.InsertParagraphAfter(); string stepForEachBasisPoint = string.Empty; for (int i = 1; i <= fucData.MethodsData[0].Method.InputPoints.Count; i++) { stepForEachBasisPoint += $"{i} = {fucData.TestFunction.GetStep(i):F2} "; } oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oPara = oDoc.Content.Paragraphs.Add(ref oRng); oPara.Range.Text = $"Шаг = [{stepForEachBasisPoint}]"; oPara.Range.Bold = 0; oPara.Range.Font.Size = 10; oPara.Format.SpaceAfter = 6; oPara.Range.InsertParagraphAfter(); oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oPara = oDoc.Content.Paragraphs.Add(ref oRng); oPara.Range.Text = $"Оценка алгоритма:"; oPara.Range.Bold = 1; oPara.Range.Font.Size = 14; oPara.Range.InsertParagraphAfter(); fucData.MethodsData.ForEach(method => { // Insert Score oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oPara = oDoc.Content.Paragraphs.Add(ref oRng); oPara.Range.Text = $"{method.Method.Name}" + $"\t\t\t{(method.Method is LagrangeInterpolation ? "\t\t\t" : "")}" + $"{method.MethodMark:F16}"; oPara.Range.Bold = 0; oPara.Range.Font.Size = 14; oPara.Range.InsertParagraphAfter(); }); // Insert Chart Image oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oPara = oDoc.Content.Paragraphs.Add(ref oRng); Clipboard.Clear(); Clipboard.SetImage(fucData.GraphicImage); oPara.Range.Paste(); oPara.Range.InsertParagraphAfter(); // Insert Space object oCollapseEnd = Word.WdCollapseDirection.wdCollapseEnd; object oPageBreak = Word.WdBreakType.wdPageBreak; oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oPara = oDoc.Content.Paragraphs.Add(ref oRng); ((Word.Range)oRng).Collapse(ref oCollapseEnd); ((Word.Range)oRng).InsertBreak(ref oPageBreak); ((Word.Range)oRng).Collapse(ref oCollapseEnd); oPara.Format.SpaceAfter = 0; oPara.Range.InsertParagraphAfter(); }); oWord.Visible = true; } catch { oWord.Visible = true; throw; } }
private void button1_Click(object sender, EventArgs e) { string dir_temp = Application.StartupPath + "\\Temp\\"; if (!System.IO.Directory.Exists(dir_temp)) { System.IO.Directory.CreateDirectory(dir_temp); } string dir_result = Application.StartupPath + "\\Объединенные файлы\\"; if (!System.IO.Directory.Exists(dir_result)) { System.IO.Directory.CreateDirectory(dir_result); } // Сборник лежит там же, где и исполняемый файл .exe string FileName = Application.StartupPath + "\\сборник.docx"; app = new Word.Application(); app.Visible = true; doc = app.Documents.Open(FileName, ReadOnly: true); // все страницы doc.SaveAs2(newFileName, // FileFormat: Word.WdSaveFormat.wdFormatPDF ); Word.Table myTable = doc.Tables[1]; // если содержание в первой таблице!!! иначе исправить int count = myTable.Rows.Count; int Num = 1; //count = 5; for (int i = 1; i <= count - 1; i++) { String articleName = myTable.Rows[i].Cells[1].Range.Text.Trim(); if (articleName.ToUpper().Contains("СЕКЦИЯ")) { continue; } int len = Math.Min(articleName.Length, 48); String name = "№" + Num + " " + translit(articleName.Substring(0, len)) + ".pdf"; String newFileName = dir_temp + name; String newFileUnionName = dir_result + name; Num++; String st_from = myTable.Rows[i].Cells[2].Range.Text; String st_to = myTable.Rows[i + 1].Cells[2].Range.Text; st_from = Regex.Replace(st_from, "[^0-9]+", string.Empty); st_to = Regex.Replace(st_to, "[^0-9]+", string.Empty); int from = Convert.ToInt32(st_from); int to = Convert.ToInt32(st_to) - 1; doc.ExportAsFixedFormat(newFileName, Word.WdExportFormat.wdExportFormatPDF, false, Word.WdExportOptimizeFor.wdExportOptimizeForPrint, Word.WdExportRange.wdExportFromTo, from, to ); using (PdfDocument one = PdfReader.Open("titul.pdf", PdfDocumentOpenMode.Import)) using (PdfDocument two = PdfReader.Open(newFileName, PdfDocumentOpenMode.Import)) using (PdfDocument outPdf = new PdfDocument()) { CopyPages(one, outPdf); CopyPages(two, outPdf); outPdf.Save(newFileUnionName); } } doc.Close(SaveChanges: false); app.Quit(); MessageBox.Show("Готово!"); }
/// <summary> /// Convert existing Word document to a specified extension and returns path to file /// </summary> public static string ConvertWord(string DocFilePathRaw, string NewFileName, string DirectoryToSaveRaw, string NewFileExtension, Word.WdSaveFormat NewFileFormat) { //calculate file name with exxtension if (!NewFileName.EndsWith("." + NewFileExtension)) { NewFileName = NewFileName + "." + NewFileExtension; } //get absolute filePaths for both the new directory and the old file path string directoryToSave = String.IsNullOrEmpty(DirectoryToSaveRaw) ? Directory.GetCurrentDirectory() : Path.GetFullPath(DirectoryToSaveRaw); string docFilePath = Path.GetFullPath(DocFilePathRaw); //calculate new File Path string newFilePath = Path.Combine(directoryToSave, NewFileName); // Open and init the Word Application. Word._Application word_app = new Word.Application(); word_app.Visible = false; word_app.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone; bool save_changes = false; //performing conversion operation try { //initialize settings bool confirm_conversions = false; bool read_only = true; bool add_to_recent_files = false; object format = 0; //open the document Word._Document word_doc = word_app.Documents.Open(docFilePath, confirm_conversions, read_only, add_to_recent_files, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); word_doc.SaveAs(newFilePath, NewFileFormat, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); //Close the document word_doc.Close(save_changes, Type.Missing, Type.Missing); } catch { throw; } finally { //Close the App word_app.Quit(); GC.Collect(); } return(newFilePath); }
public static void foo() { object oMissing = System.Reflection.Missing.Value; object oEndOfDoc = "\\endofdoc"; Word._Application oWord = new Word.Application(); Word._Document oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); oWord.Visible = true; Word.Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; //Insert a chart. Word.InlineShape oShape; object oClassType = "MSGraph.Chart.8"; wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oShape = wrdRng.InlineShapes.AddOLEObject(ref oClassType, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); //Demonstrate use of late bound oChart and oChartApp objects to //manipulate the chart object with MSGraph. object oChart; object oChartApp; oChart = oShape.OLEFormat.Object; oChartApp = oChart.GetType().InvokeMember("Application", BindingFlags.GetProperty, null, oChart, null); //Change the chart type to Line. object[] Parameters = new Object[1]; Parameters[0] = 2; //xlLine = 4 oChart.GetType().InvokeMember("ChartType", BindingFlags.SetProperty, null, oChart, Parameters); //Update the chart image and quit MSGraph. oChartApp.GetType().InvokeMember("Update", BindingFlags.InvokeMethod, null, oChartApp, null); oChartApp.GetType().InvokeMember("Quit", BindingFlags.InvokeMethod, null, oChartApp, null); //... If desired, you can proceed from here using the Microsoft Graph //Object model on the oChart and oChartApp objects to make additional //changes to the chart. //Set the width of the chart. oShape.Width = oWord.InchesToPoints(6.25f); oShape.Height = oWord.InchesToPoints(3.57f); //Add text after the chart. wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; wrdRng.InsertParagraphAfter(); wrdRng.InsertAfter("THE END."); }
public static bool convertToNewOfficeDocument(string fileName, out string newFileName, out string newExt) { string ext = Path.GetExtension(fileName); newExt = ext; newFileName = fileName; if (!destinationDictionary.ContainsKey(ext)) { return(false); } officeDestination dest = destinationDictionary[ext]; newExt = dest.Extension; newFileName = fileName.Replace(ext, dest.Extension); object obj; bool result = true; switch (dest.Application) { case officeApplication.Word: Word._Application wordApp = new Word.Application(); Word._Document wordDoc = null; try { wordDoc = wordApp.Documents.Open(fileName); wordDoc.Convert(); wordDoc.SaveAs(newFileName, dest.FileFormat); } catch (Exception e) { displayError(fileName, e); newFileName = fileName; result = false; } finally { wordDoc.Close(); wordApp.Quit(); obj = (object)wordDoc; disposeInteropObject(ref obj); obj = (object)wordApp; disposeInteropObject(ref obj); } break; case officeApplication.Excel: Excel._Application excelApp = new Excel.Application(); Excel._Workbook excelDoc = null; try { excelDoc = excelApp.Workbooks.Open(fileName); excelDoc.SaveAs(newFileName, dest.FileFormat); } catch (Exception e) { displayError(fileName, e); newFileName = fileName; result = false; } finally { excelDoc.Close(); excelApp.Quit(); obj = (object)excelDoc; disposeInteropObject(ref obj); obj = (object)excelApp; disposeInteropObject(ref obj); } break; case officeApplication.PowerPoint: PowerPoint._Application powerpointApp = new PowerPoint.Application(); PowerPoint._Presentation powerpointDoc = null; try { powerpointDoc = powerpointApp.Presentations.Open(fileName, MsoTriState.msoTrue, MsoTriState.msoTrue, MsoTriState.msoFalse); powerpointDoc.SaveAs(newFileName, (PowerPoint.PpSaveAsFileType)dest.FileFormat); } catch (Exception e) { displayError(fileName, e); newFileName = fileName; result = false; } finally { powerpointDoc.Close(); powerpointApp.Quit(); obj = (object)powerpointDoc; disposeInteropObject(ref obj); obj = (object)powerpointApp; disposeInteropObject(ref obj); } break; } GC.Collect(); return(result); }
private void mbPrint_Click(object sender, EventArgs e) { try { Word.Selection wrdSelection; Word.Table wrdTable; string StrToAdd; // открываем Word и делаем его видимым wrdApp = new Word.Application(); wrdApp.Visible = true; // создаем документ wrdDoc = wrdApp.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); wrdDoc.Select(); wrdSelection = wrdApp.Selection; // Заголовок документа. StrToAdd = "Отчет"; wrdSelection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; wrdSelection.TypeText(StrToAdd); InsertLines(2); //выравнивание по правому краю и ставка времени и даты wrdSelection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight; Object objDate = "Дата составления: dddd, MMMM dd, yyyy" + " г."; wrdSelection.InsertDateTime(ref objDate, ref oFalse, ref oMissing, ref oMissing, ref oMissing); InsertLines(2); if (this.metroGrid1.Rows.Count <= 0) { StrToAdd = "Таблица пустая"; wrdSelection.TypeText(StrToAdd); } else { wrdTable = wrdDoc.Tables.Add(wrdSelection.Range, this.metroGrid1.Rows.Count + 1, 4, ref oMissing, ref oMissing); //Параметры таблицы wrdTable.Columns[1].SetWidth(100, Word.WdRulerStyle.wdAdjustNone); wrdTable.Columns[2].SetWidth(170, Word.WdRulerStyle.wdAdjustNone); wrdTable.Columns[3].SetWidth(100, Word.WdRulerStyle.wdAdjustNone); wrdTable.Columns[4].SetWidth(111, Word.WdRulerStyle.wdAdjustNone); wrdTable.Rows[1].Cells.Shading.BackgroundPatternColorIndex = Word.WdColorIndex.wdGray25; wrdTable.Rows[1].Range.Bold = 1; wrdTable.Cell(1, 1).Range.Paragraphs.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; //отрисовка таблицы wrdTable.Borders[Word.WdBorderType.wdBorderBottom].LineStyle = Word.WdLineStyle.wdLineStyleSingle; wrdTable.Borders[Word.WdBorderType.wdBorderTop].LineStyle = Word.WdLineStyle.wdLineStyleSingle; wrdTable.Borders[Word.WdBorderType.wdBorderVertical].LineStyle = Word.WdLineStyle.wdLineStyleSingle; wrdTable.Borders[Word.WdBorderType.wdBorderHorizontal].LineStyle = Word.WdLineStyle.wdLineStyleSingle; wrdTable.Borders[Word.WdBorderType.wdBorderLeft].LineStyle = Word.WdLineStyle.wdLineStyleSingle; wrdTable.Borders[Word.WdBorderType.wdBorderRight].LineStyle = Word.WdLineStyle.wdLineStyleSingle; FillRow(wrdDoc, 1, "Наименование", "Остаток", "Необходимо", "Надо заказать"); for (int i = 2; i <= this.metroGrid1.Rows.Count + 1; i++) { if ((Convert.ToInt32(this.metroGrid1[4, i].Value) - Convert.ToInt32(this.metroGrid1[5, i].Value)) >= 0) { FillRow(wrdDoc, i, this.metroGrid1[0, i].Value.ToString(), this.metroGrid1[5, i].Value.ToString(), this.metroGrid1[4, i].Value.ToString(), Convert.ToString(Convert.ToInt32(this.metroGrid1[4, i].Value) - Convert.ToInt32(this.metroGrid1[5, i].Value))); } else { FillRow(wrdDoc, i, this.metroGrid1[0, i].Value.ToString(), this.metroGrid1[5, i].Value.ToString(), this.metroGrid1[4, i].Value.ToString(), "Не требуется"); } } } } catch (Exception ex) { } }
private void ButtonPrintLetter_Click(object sender, RoutedEventArgs e) { try { if (TextBlockDataFilePatch.Text == "") { return; } if (TextBlockTemplateFilePatch.Text == "") { return; } FileInfo fiDataFilePatch = new FileInfo(TextBlockDataFilePatch.Text); FileInfo fiTemplateFilePatch = new FileInfo(TextBlockTemplateFilePatch.Text); // Проверяем, что выбранные файлы существуют if (fiDataFilePatch.Exists && fiTemplateFilePatch.Exists) { // Открываем файл Excel с данными Excel.Application excel = new Excel.Application(); Excel.Workbook wbv = excel.Workbooks.Open(TextBlockDataFilePatch.Text, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0); Excel.Worksheet wx = (Excel.Worksheet)wbv.Worksheets.get_Item(1); // word - файл с шаблоном пригласительного письма, // в нем далее будут формироваться (добавляться в конец) // письма по всем компаниям Word._Application word = new Word.Application(); // word2 - файл с шаблоном пригласительного письма, // который используется единожды для заполнения // данных по конкретной компании, после чего // листы добавляются в конец word Word._Application word2 = new Word.Application(); // Открываем файл шаблоном пригласительного письма Word.Document wordFile = word.Documents.Open(TextBlockTemplateFilePatch.Text); // Номер строки, в которой указана первая компания int i = Convert.ToInt32(TextBoxNumberFrom.Text.ToString()); // Заполняются данные по первой компании wordFile.FormFields["ТекстовоеПоле1"].Range.Text = wx.Cells[i, 4].Text; wordFile.FormFields["ТекстовоеПоле2"].Range.Text = wx.Cells[i, 2].Text; wordFile.FormFields["ТекстовоеПоле3"].Range.Text = wx.Cells[i, 8].Text; wordFile.FormFields["ТекстовоеПоле4"].Range.Text = wx.Cells[i, 3].Text; wordFile.FormFields["ТекстовоеПоле5"].Range.Text = wx.Cells[i, 6].Text; wordFile.FormFields["ТекстовоеПоле6"].Range.Text = wx.Cells[i, 7].Text; // В конец файла добавляется новый пустой абзац object oEndofDoc = "\\endofdoc"; object oRng = wordFile.Bookmarks.get_Item(ref oEndofDoc).Range; Word.Paragraph par = wordFile.Content.Paragraphs.Add(ref oRng); // В конец файла добавляется разрыв страницы object unit; object extend; unit = Word.WdUnits.wdStory; extend = Word.WdMovementType.wdMove; word.Selection.EndKey(ref unit, ref extend); object oType; oType = Word.WdBreakType.wdSectionBreakNextPage; word.Selection.InsertBreak(ref oType); // После разрыва страницы снова добавляется пустой абзац oRng = wordFile.Bookmarks.get_Item(ref oEndofDoc).Range; par = wordFile.Content.Paragraphs.Add(ref oRng); object missing = System.Reflection.Missing.Value; object readOnly = true; // Запоминаем номер строки, до которой необходимо вывести данные int N = Convert.ToInt32(TextBoxNumberBefor.Text.ToString()); for (i++; i <= N; i++) { // Открываем файл с шаблоном пригласительного письма Word._Document oDoc = word2.Documents.Open(TextBlockTemplateFilePatch.Text, 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.Range oRange = oDoc.Content; // Заполняются данные по первой компании oDoc.FormFields["ТекстовоеПоле1"].Range.Text = wx.Cells[i, 4].Text; oDoc.FormFields["ТекстовоеПоле2"].Range.Text = wx.Cells[i, 2].Text; oDoc.FormFields["ТекстовоеПоле3"].Range.Text = wx.Cells[i, 8].Text; oDoc.FormFields["ТекстовоеПоле4"].Range.Text = wx.Cells[i, 3].Text; oDoc.FormFields["ТекстовоеПоле5"].Range.Text = wx.Cells[i, 6].Text; oDoc.FormFields["ТекстовоеПоле6"].Range.Text = wx.Cells[i, 7].Text; // Копируем шаблон с заполненными данными в буфер обмена oRange.Copy(); // Вставляем из буфера обмена страницы в конец wordFile par.Range.Paste(); // В конец файла wordFile добавляется разрыв страницы unit = Word.WdUnits.wdStory; extend = Word.WdMovementType.wdMove; word.Selection.EndKey(ref unit, ref extend); oType = Word.WdBreakType.wdSectionBreakNextPage; word.Selection.InsertBreak(ref oType); // В конец файла wordFile добавляется разрыв страницы oRng = wordFile.Bookmarks.get_Item(ref oEndofDoc).Range; par = wordFile.Content.Paragraphs.Add(ref oRng); // Закрываем файл oDoc oDoc.Close(false, Type.Missing, Type.Missing); } // Показывваем файл со всеми заполненными пригласительными письмами word.Visible = true; // Сохраняем файл //SaveAsFile(wordFile); //wordFile.Close(); // Закрываем исходный файл Excel с данными wbv.Close(false, Type.Missing, Type.Missing); excel.Quit(); } else { MessageBox.Show("Выберитие файл шаблона и файл с данными"); } } catch (Exception ex) { // Показываем сообщение об ошибке MessageBox.Show(ex.Message); } }
public void MakeReport(DataGridView WorkerGrid, DataGridView WorkGrid, DataGridView InstructionGrid) { string[,] Worker = SaveDataFromDGV(WorkerGrid); string[,] Instruction = SaveInstructionAndWorkFromDGV(InstructionGrid); application = new Word.Application(); object templatePathObj = Application.StartupPath + @"\Template.docx"; try { document = application.Documents.Add(ref templatePathObj, ref missingObj, ref missingObj, ref missingObj); } catch (Exception error) { document.Close(ref falseObj, ref missingObj, ref missingObj); application.Quit(ref missingObj, ref missingObj, ref missingObj); document = null; application = null; //throw error; MessageBox.Show(error.ToString(), "OK", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1); } application.Visible = true; object bookmarkObj = "Naryad_Number"; Word.Range bookmarkRange = document.Bookmarks.get_Item(ref bookmarkObj).Range; bookmarkRange.Text = form.naryadNomer.Text; bookmarkObj = "Naryad_Date"; bookmarkRange = document.Bookmarks.get_Item(ref bookmarkObj).Range; bookmarkRange.Text = form.Date.Text; Thread.Sleep(1000); bookmarkObj = "Workman"; bookmarkRange = document.Bookmarks.get_Item(ref bookmarkObj).Range; bookmarkRange.Text = form.workman.Text; bookmarkObj = "AmountWorkers"; bookmarkRange = document.Bookmarks.get_Item(ref bookmarkObj).Range; bookmarkRange.Text = WorkerGrid.SelectedRows.Count.ToString(); bookmarkObj = "WorkStart"; bookmarkRange = document.Bookmarks.get_Item(ref bookmarkObj).Range; bookmarkRange.Text = form.workStart.Text; bookmarkObj = "Date"; bookmarkRange = document.Bookmarks.get_Item(ref bookmarkObj).Range; bookmarkRange.Text = form.Date.Text; bookmarkObj = "WorkEnd"; bookmarkRange = document.Bookmarks.get_Item(ref bookmarkObj).Range; bookmarkRange.Text = form.workEnd.Text; bookmarkObj = "Date2"; bookmarkRange = document.Bookmarks.get_Item(ref bookmarkObj).Range; bookmarkRange.Text = form.Date.Text; bookmarkObj = "Head"; bookmarkRange = document.Bookmarks.get_Item(ref bookmarkObj).Range; bookmarkRange.Text = form.head.Text; bookmarkObj = "Date3"; bookmarkRange = document.Bookmarks.get_Item(ref bookmarkObj).Range; bookmarkRange.Text = form.Date.Text; Print("WhatWork", WorkGrid); Print("Instruction", InstructionGrid); Print("InstructionID", InstructionGrid); bookmarkObj = "AmountWorkers2"; bookmarkRange = document.Bookmarks.get_Item(ref bookmarkObj).Range; bookmarkRange.Text = WorkerGrid.SelectedRows.Count.ToString(); Word.Table _table = document.Tables[1]; Word.Range _currentRange; for (int i = 0; i < WorkerGrid.SelectedRows.Count; i++) { _currentRange = _table.Cell(i + 2, 2).Range; _currentRange.Text = Worker[i, 0]; _currentRange = _table.Cell(i + 2, 3).Range; _currentRange.Text = Worker[i, 1]; } document.Close(Word.WdSaveOptions.wdSaveChanges); application.Quit(); }
private Word._Document GetDoc(string path) { Word._Document oDoc = _oWord.Documents.Add(path); SetTemplate(oDoc); return(oDoc); }
private void WriteLineToRoSDOld(TreeNode tn, WordNet._Document oDoc, WordNet.Table oTable, string prefix = "", string parent = "", int seqnum = 0) { if (tn.Tag == null || tn.Tag.GetType().Name != "scClientDocSetDocLink") { // still need to check subnodes } else { int x = 0; foreach (TreeNode node in tn.Nodes) { x++; row++; scClientDocSetDocLink documentClient = (scClientDocSetDocLink)node.Tag; // First column string currentParent = ""; if (string.IsNullOrEmpty(parent)) { currentParent = x.ToString(); } else { currentParent = parent + "." + x.ToString(); } oTable.Cell(row, 1).Width = 30; oTable.Cell(row, 1).Range.Text = currentParent; oTable.Cell(row, 2).Width = 30; System.Drawing.Bitmap bitmap1 = Properties.Resources.FolderIcon; if (documentClient.document.RecordType.Trim() == FCMConstant.RecordType.FOLDER) { bitmap1 = Properties.Resources.FolderIcon; } else { bitmap1 = Properties.Resources.WordIcon; if (documentClient.document.DocumentType == MackkadoITFramework.Helper.Utils.DocumentType.EXCEL) { bitmap1 = Properties.Resources.ExcelIcon; } if (documentClient.document.DocumentType == MackkadoITFramework.Helper.Utils.DocumentType.PDF) { bitmap1 = Properties.Resources.PDFIcon; } } Clipboard.SetImage(bitmap1); oTable.Cell(row, 2).Range.Paste(); oTable.Cell(row, 3).Width = 60; oTable.Cell(row, 3).Range.Text = prefix + documentClient.document.CUID; oTable.Cell(row, 4).Width = 50; oTable.Cell(row, 4).Range.Text = prefix + documentClient.document.IssueNumber.ToString("000"); oTable.Cell(row, 5).Width = 300; oTable.Cell(row, 5).Range.Text = prefix + documentClient.document.Name; oTable.Cell(row, 6).Width = 100; oTable.Cell(row, 6).Range.Text = "???"; if (uioutput != null) { uioutput.AddOutputMessage(documentClient.document.Name, "", ""); } if (node.Nodes.Count > 0) { WriteLineToRoSD(node, oDoc, oTable, prefix: "", parent: currentParent, seqnum: x); } } } }
private void buttonConvert_Click(object sender, EventArgs e) { _oWord = new Word.Application(); _oWord.Visible = true; Word._Document oDoc = GetDoc(@"e:\Заказ\ValentinDiplom\Diplom\Diplom\bin\Debug\Лечение.docx"); }
public static void CloseWordFile(Word._Application oWord, Word._Document oDoc) { oDoc.Close(); oWord.Quit(); }
private void SetTemplate(Word._Document oDoc) { oDoc.Bookmarks["Лечение"].Range.Text = panelAdd.Controls["textBoxTreatment"].Text; oDoc.Bookmarks["Дата"].Range.Text = DateTime.Now.ToShortDateString(); }
private void CreateWordDocument() { //создаем обьект приложения word m_app = new Microsoft.Office.Interop.Word.Application(); // создаем путь к файлу Object templatePathObj = System.IO.Path.GetTempFileName(); // если вылетим не этом этапе, приложение останется открытым try { m_doc = m_app.Documents.Add(ref templatePathObj, ref missingObj, ref missingObj, ref missingObj); } catch (Exception error) { m_doc.Close(ref falseObj, ref missingObj, ref missingObj); m_app.Quit(ref missingObj, ref missingObj, ref missingObj); m_doc = null; m_app = null; throw error; } //m_app.Visible = true; }
private void tableMain(object ObjMissing, Word._Document ObjDoc) { int curRow; int countCol; int countRow; string[] FIO; string Surname; string Name; string Patronymic; string Addition; //Задаём закладку конца документа object EndOfDoc = "\\endofdoc"; Word.Table ObjTable; Word.Range ObjWordRange; //Задаём количество столбцов //оно остаётся неизменным //в количестве 6 штук countCol = 6; //Создаём строки //1. под шапку таблицы countRow = 1; //Формируем строки по заменам преподавателей в первом семестре //прогоняем все строки фактической нагрузки for (int i = 0; i <= mdlData.colDistribution.Count - 1; i++) { //смотрим только второй семестр if (mdlData.colDistribution[i].Semestr.SemNum.Equals(cmbSemestr.SelectedItem.ToString())) { //Если есть часы на ГАК, на аспирантуру, на диплом, //на преддипломную практику, на производственную практику, //на посещение учебных занятий, //на учебную практику, то не рассматриваем эти строки if (!(mdlData.colDistribution[i].GAK > 0) & !(mdlData.colDistribution[i].PostGrad > 0) & !(mdlData.colDistribution[i].DiplomaPaper > 0) & !(mdlData.colDistribution[i].PreDiplomaPractice > 0) & !(mdlData.colDistribution[i].ProducingPractice > 0) & !(mdlData.colDistribution[i].TutorialPractice > 0) & !(mdlData.colDistribution[i].Visiting > 0)) { if ((mdlData.colDistribution[i].Subject.Subject == "Посещение занятий") || (mdlData.colDistribution[i].Subject.Subject == "Аспирантура") || (mdlData.colDistribution[i].Subject.Subject == "Руководство магистрами")) { continue; } //добавляем строку countRow++; } } } //Вставляем таблицу согласно заполненной сетке и заполняем её данными о нагрузке ObjWordRange = ObjDoc.Bookmarks.get_Item(ref EndOfDoc).Range; ObjTable = ObjDoc.Tables.Add(ObjWordRange, countRow, countCol, ref ObjMissing, ref ObjMissing); //Размер шрифта 10 пт ObjTable.Range.Font.Size = 10; //Выравнивание по левому краю ObjTable.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft; //Отступ после абзаца отсутствует ObjTable.Range.ParagraphFormat.SpaceAfter = 0; //Отступ в 0 пт до абзаца ObjTable.Range.ParagraphFormat.SpaceBefore = 0; //Одинарный межстрочный интервал ObjTable.Range.ParagraphFormat.Space1(); //Границы таблицы включены ObjTable.Borders.Enable = 1; //Текущая строка первая curRow = 1; ObjTable.Rows[1].Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; ObjTable.Rows[1].Range.Font.Bold = 1; //Заполняем первую строку и одновременно формируем размерности ObjTable.Cell(curRow, 1).Range.Text = "№ п/п"; ObjTable.Cell(curRow, 2).Range.Text = "Дисциплина"; ObjTable.Cell(curRow, 3).Range.Text = "Группа"; ObjTable.Cell(curRow, 4).Range.Text = "Основной преподаватель"; ObjTable.Cell(curRow, 5).Range.Text = "Замещающий преподаватель"; ObjTable.Cell(curRow, 6).Range.Text = "Резервный преподаватель"; //Формируем строки по заменам преподавателей в первом семестре //прогоняем все строки фактической нагрузки for (int i = 0; i <= mdlData.colDistribution.Count - 1; i++) { //смотрим только второй семестр if (mdlData.colDistribution[i].Semestr.SemNum.Equals(cmbSemestr.SelectedItem.ToString())) { //Если есть часы на ГАК, на аспирантуру, на диплом, //на преддипломную практику, на производственную практику, //на посещение учебных занятий, //на учебную практику, то не рассматриваем эти строки if (!(mdlData.colDistribution[i].GAK > 0) & !(mdlData.colDistribution[i].PostGrad > 0) & !(mdlData.colDistribution[i].DiplomaPaper > 0) & !(mdlData.colDistribution[i].PreDiplomaPractice > 0) & !(mdlData.colDistribution[i].ProducingPractice > 0) & !(mdlData.colDistribution[i].TutorialPractice > 0) & !(mdlData.colDistribution[i].Visiting > 0)) { if ((mdlData.colDistribution[i].Subject.Subject == "Посещение занятий") || (mdlData.colDistribution[i].Subject.Subject == "Аспирантура") || (mdlData.colDistribution[i].Subject.Subject == "Руководство магистрами")) { continue; } //счётчик текущей строки увеличиваем на единицу curRow += 1; //дополнение к названию дисциплины Addition = "("; //Если есть лекционные часы if (mdlData.colDistribution[i].Lecture > 0) { //пишем про наличие лекции Addition += "лк,"; } //Если уже дописали вид нагрузки, то более ничего не пишем if (!(Addition.EndsWith(","))) { //Если есть практические часы if (mdlData.colDistribution[i].Practice > 0) { //пишем про наличие практических Addition += "пр,"; } } //Если уже дописали вид нагрузки, то более ничего не пишем if (!(Addition.EndsWith(","))) { //Если есть лабораторные часы if (mdlData.colDistribution[i].LabWork > 0) { //пишем про наличие лабораторных Addition += "лб,"; } } //Если уже дописали вид нагрузки, то более ничего не пишем if (!(Addition.EndsWith(","))) { //Если есть курсовой проект if (mdlData.colDistribution[i].KursProject > 0) { //пишем про наличие курсового проекта Addition += "к/пр,"; } } //Убираем запятую if (Addition.EndsWith(",")) { Addition = Addition.Substring(0, Addition.Length - 1); } //Закрываем скобку Addition += ")"; //Если внутри скобок пустота, то if (Addition == "()") { //убираем скобки Addition = ""; } //В номер по порядку вписываем значение счётчика ObjTable.Cell(curRow, 1).Range.Text = (curRow - 1).ToString(); //Вписываем название дисциплины с дополнением ObjTable.Cell(curRow, 2).Range.Text = mdlData.colDistribution[i].Subject.Subject.ToString() + " " + Addition; //Название группы с номером курса if (!(mdlData.colDistribution[i].Speciality == null) & !(mdlData.colDistribution[i].KursNum == null)) { ObjTable.Cell(curRow, 3).Range.Text = mdlData.colDistribution[i].Speciality.ShortInstitute.ToString() + "-" + mdlData.colDistribution[i].KursNum.Kurs.ToString(); } else { if (!(mdlData.colDistribution[i].Speciality == null)) { ObjTable.Cell(curRow, 3).Range.Text = mdlData.colDistribution[i].Speciality.ShortInstitute.ToString(); } else { if (!(mdlData.colDistribution[i].KursNum == null)) { ObjTable.Cell(curRow, 3).Range.Text = "???-" + mdlData.colDistribution[i].KursNum.Kurs.ToString(); } } } //Разбираем строку для вывода отдельно //Фамилии, имени и отчества основного преподавателя if (mdlData.colDistribution[i].Lecturer != null) { FIO = mdlData.colDistribution[i].Lecturer.FIO.Split(new char[] { ' ' }); if (FIO.GetLength(0) == 3) { Surname = FIO[0]; Name = FIO[1].Substring(0, 1) + "."; Patronymic = FIO[2].Substring(0, 1) + "."; } else if (FIO.GetLength(0) == 2) { Surname = FIO[0]; Name = FIO[1].Substring(0, 1) + "."; Patronymic = ""; } else if (FIO.GetLength(0) == 1) { Surname = FIO[0]; Name = ""; Patronymic = ""; } else { Surname = ""; Name = ""; Patronymic = ""; } ObjTable.Cell(curRow, 4).Range.Text = Surname + " " + Name + Patronymic; } //Разбираем строку для вывода отдельно //Фамилии, имени и отчества заменяющего преподавателя if (!(mdlData.colDistribution[i].Lecturer2 == null)) { FIO = mdlData.colDistribution[i].Lecturer2.FIO.Split(new char[] { ' ' }); if (FIO.GetLength(0) == 3) { Surname = FIO[0]; Name = FIO[1].Substring(0, 1) + "."; Patronymic = FIO[2].Substring(0, 1) + "."; } else if (FIO.GetLength(0) == 2) { Surname = FIO[0]; Name = FIO[1].Substring(0, 1) + "."; Patronymic = ""; } else if (FIO.GetLength(0) == 1) { Surname = FIO[0]; Name = ""; Patronymic = ""; } else { Surname = ""; Name = ""; Patronymic = ""; } ObjTable.Cell(curRow, 5).Range.Text = Surname + " " + Name + Patronymic; } //Разбираем строку для вывода отдельно //Фамилии, имени и отчества резервного преподавателя if (!(mdlData.colDistribution[i].Lecturer3 == null)) { FIO = mdlData.colDistribution[i].Lecturer3.FIO.Split(new char[] { ' ' }); if (FIO.GetLength(0) == 3) { Surname = FIO[0]; Name = FIO[1].Substring(0, 1) + "."; Patronymic = FIO[2].Substring(0, 1) + "."; } else if (FIO.GetLength(0) == 2) { Surname = FIO[0]; Name = FIO[1].Substring(0, 1) + "."; Patronymic = ""; } else if (FIO.GetLength(0) == 1) { Surname = FIO[0]; Name = ""; Patronymic = ""; } else { Surname = ""; Name = ""; Patronymic = ""; } ObjTable.Cell(curRow, 6).Range.Text = Surname + " " + Name + Patronymic; } } } } ObjTable.Columns[1].Width = 0.94f / 0.03527f; ObjTable.Columns[2].Width = 7.05f / 0.03527f; ObjTable.Columns[3].Width = 1.70f / 0.03527f; ObjTable.Columns[4].Width = 3.09f / 0.03527f; ObjTable.Columns[5].Width = 3.62f / 0.03527f; ObjTable.Columns[6].Width = 3.43f / 0.03527f; }
// создаем приложение Word и открывает новый документ по заданному файлу шаблона public void CreateFromTemplate(string templatePath) { //создаем обьект приложения word wordApplication = new Word.Application(); wordApplication.Visible = false; // создаем путь к файлу используя имя файла templatePathObj = templatePath; //создаем ноый документ методом приложения Word по поути к шаблону документа try { wordDocument = wordApplication.Documents.Open(templatePath); //wordDocument = wordApplication.Documents.Add(ref templatePathObj,ref wordMissing, ref wordMissing, true); } // если произошла ошибка, то приложение Word надо закрыть catch (Exception error) { wordApplication.Quit(ref wordMissing, ref wordMissing, ref wordMissing); wordApplication = null; throw new Exception("Ошибка. Не удалось открыть шаблон документа MS Word. " + error.Message); } // завершение createFromTemplate(string templatePath) }
public void ExecuteStartCommand() { object missingObj = System.Reflection.Missing.Value; object trueObj = true; object falseObj = false; //создаем обьект приложения word application = new Word.Application(); // создаем путь к файлу object templatePathObj = "D:\\tmp\\test.docx";; // если вылетим не этом этапе, приложение останется открытым //document = application.Documents.Add(ref templatePathObj, ref missingObj, ref missingObj, ref missingObj); //Word._Document docnew = application.Documents.Add(); try { document = application.Documents.Add(ref templatePathObj, ref missingObj, ref missingObj, ref missingObj); } catch (Exception error) { //document.Close(ref falseObj, ref missingObj, ref missingObj); application.Quit(ref missingObj, ref missingObj, ref missingObj); document = null; application = null; throw error; } application.Visible = true; Word.Range bookmarkRange; bookmarkRange = document.Bookmarks["Num"].Range; bookmarkRange.Text = Contract.Num; bookmarkRange = document.Bookmarks["Num1"].Range; bookmarkRange.Text = Contract.Num; bookmarkRange = document.Bookmarks["Date"].Range; bookmarkRange.Text = Contract.Date.ToString("dd.MM.yyyy"); bookmarkRange = document.Bookmarks["Date1"].Range; bookmarkRange.Text = Contract.Date.ToString("dd.MM.yyyy"); if (Contract.CustomerStatus == Status.езидент) { bookmarkRange = document.Bookmarks["NotRezident"].Range; bookmarkRange.Delete(); } if (Contract.Signatory != null) { switch (Contract.Signatory.Id) { case "Signatory1": DelBookmark("Signatory2"); DelBookmark("Dover2"); DelBookmark("Sign2"); DelBookmark("Signatory3"); DelBookmark("Dover3"); DelBookmark("Sign3"); DelBookmark("Signatory4"); DelBookmark("Dover4"); DelBookmark("Sign4"); DelBookmark("Signatory5"); DelBookmark("Dover5"); DelBookmark("Sign5"); break; case "Signatory2": DelBookmark("Signatory1"); DelBookmark("Dover1"); DelBookmark("Sign1"); DelBookmark("Signatory3"); DelBookmark("Dover3"); DelBookmark("Sign3"); DelBookmark("Signatory4"); DelBookmark("Dover4"); DelBookmark("Sign4"); DelBookmark("Signatory5"); DelBookmark("Dover5"); DelBookmark("Sign5"); break; case "Signatory3": DelBookmark("Signatory1"); DelBookmark("Dover1"); DelBookmark("Sign1"); DelBookmark("Signatory2"); DelBookmark("Dover2"); DelBookmark("Sign2"); DelBookmark("Signatory4"); DelBookmark("Dover4"); DelBookmark("Sign4"); DelBookmark("Signatory5"); DelBookmark("Dover5"); DelBookmark("Sign5"); break; case "Signatory4": DelBookmark("Signatory1"); DelBookmark("Dover1"); DelBookmark("Sign1"); DelBookmark("Signatory2"); DelBookmark("Dover2"); DelBookmark("Sign2"); DelBookmark("Signatory3"); DelBookmark("Dover3"); DelBookmark("Sign3"); DelBookmark("Signatory5"); DelBookmark("Dover5"); DelBookmark("Sign5"); break; case "Signatory5": DelBookmark("Signatory1"); DelBookmark("Dover1"); DelBookmark("Sign1"); DelBookmark("Signatory2"); DelBookmark("Dover2"); DelBookmark("Sign2"); DelBookmark("Signatory3"); DelBookmark("Dover3"); DelBookmark("Sign3"); DelBookmark("Signatory4"); DelBookmark("Dover4"); DelBookmark("Sign4"); break; } } }
// закрытие открытого документа и приложения public void Close() { if (documentClosed()) { throw new Exception("Ошибка при попытке закрыть Microsoft Word. Программа или документ уже закрыты."); } wordDocument.Close(ref wordFalse, ref wordMissing, ref wordMissing); wordApplication.Quit(ref wordMissing, ref wordMissing, ref wordMissing); wordDocument = null; wordApplication = null; }
private void SaveAsWordDocument() { DateTime beginSessionDate, endSessionDate; DetectSessionDates(out beginSessionDate, out endSessionDate); object oMissing = System.Reflection.Missing.Value; object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */ //Start Word and create a new document. Word._Application oWord = new Word.Application(); oWord.Visible = true; Word._Document oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); oDoc.PageSetup.TopMargin = oWord.CentimetersToPoints(1); oDoc.PageSetup.BottomMargin = oWord.CentimetersToPoints(1); oDoc.PageSetup.LeftMargin = oWord.CentimetersToPoints(1); oDoc.PageSetup.RightMargin = oWord.CentimetersToPoints(1); var faculties = _sRepo.GetAllFaculties(); for (int facCounter = 0; facCounter < Constants.Constants.facultyGroups.Keys.Count; facCounter++) { var groupIds = new List <int>(); foreach (var group in Constants.Constants.facultyGroups.ElementAt(facCounter).Value) { var groupId = _sRepo.FindStudentGroup(group); if (groupId != null) { groupIds.Add(groupId.StudentGroupId); } } var facultyExams = _repo.GetFacultyExams(_sRepo, groupIds); facultyExams = facultyExams.OrderBy(fe => fe.Key).ToDictionary((keyItem) => keyItem.Key, (valueItem) => valueItem.Value); Word.Paragraph oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing); oPara1.Range.Font.Size = 24; oPara1.Format.LineSpacing = oWord.LinesToPoints(1); oPara1.Range.Text = "Расписание"; oPara1.Format.SpaceAfter = 0; oPara1.Range.InsertParagraphAfter(); oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing); oPara1.Range.Font.Size = 14; oPara1.Format.SpaceAfter = 0; if (beginSessionDate.Month < 3) { var startYear = beginSessionDate.Year - 1; oPara1.Range.Text = "зимней сессии " + startYear + "-" + (startYear + 1) + " учебного года" + Environment.NewLine + Constants.Constants.facultyTitles[facCounter]; } else { var startYear = beginSessionDate.Year - 1; oPara1.Range.Text = "летней сессии " + startYear + "-" + (startYear + 1) + " учебного года" + Environment.NewLine + Constants.Constants.facultyTitles[facCounter]; } oPara1.Range.InsertParagraphAfter(); Word.Shape signBox = oDoc.Shapes .AddTextbox(MsoTextOrientation.msoTextOrientationHorizontal, 350, 15, 200, 75, oPara1.Range); signBox.Line.Visible = MsoTriState.msoFalse; signBox.TextFrame.ContainingRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight; signBox.TextFrame.ContainingRange.InsertAfter("«УТВЕРЖДАЮ»"); signBox.TextFrame.ContainingRange.InsertParagraphAfter(); signBox.TextFrame.ContainingRange.InsertAfter("Проректор по учебной работе"); signBox.TextFrame.ContainingRange.InsertParagraphAfter(); signBox.TextFrame.ContainingRange.InsertAfter("____________ А.В. Синицкий"); var groups = Constants.Constants.facultyGroups.ElementAt(facCounter).Value; Word.Table oTable; Word.Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oTable = oDoc.Tables.Add(wrdRng, 1 + facultyExams.Keys.Count, 1 + groups.Count); //oTable.Rows(1).HeadingFormat = True; //oTable.ApplyStyleHeadingRows = True; oTable.Rows[1].HeadingFormat = -1; oTable.ApplyStyleHeadingRows = true; oTable.Borders.Enable = 1; for (int i = 1; i <= oTable.Rows.Count; i++) { oTable.Rows[i].AllowBreakAcrossPages = (int)Microsoft.Office.Core.MsoTriState.msoFalse; } oTable.Cell(1, 1).Range.Text = "Дата"; oTable.Cell(1, 1).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; for (var column = 1; column <= groups.Count; column++) { oTable.Cell(1, column + 1).Range.Text = groups[column - 1]; oTable.Cell(1, column + 1).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; } for (var row = 2; row <= 1 + facultyExams.Keys.Count; row++) { oTable.Cell(row, 1).Range.Text = facultyExams.Keys.ElementAt(row - 2).ToString("dd MMMM yyyy", CultureInfo.CreateSpecificCulture("ru-RU")); oTable.Cell(row, 1).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; oTable.Cell(row, 1).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; } DateTime currentDate; for (var row = 2; row <= 1 + facultyExams.Keys.Count; row++) { currentDate = facultyExams.Keys.ElementAt(row - 2); for (var column = 1; column <= groups.Count; column++) { if (facultyExams.ContainsKey(currentDate)) { if (facultyExams[currentDate].ContainsKey(groupIds[column - 1])) { var eventCount = facultyExams[currentDate][groupIds[column - 1]].Count; oTable.Cell(row, column + 1).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; var timeTable = oDoc.Tables.Add(oTable.Cell(row, column + 1).Range, 1, 1); timeTable.AutoFitBehavior(Microsoft.Office.Interop.Word.WdAutoFitBehavior.wdAutoFitWindow); if (eventCount > 1) { for (int i = 1; i < eventCount; i++) { timeTable.Rows.Add(); } } for (int i = 0; i < eventCount; i++) { string cellText = ""; var evt = facultyExams[currentDate][groupIds[column - 1]][i]; // Консультация || Экзамен if (evt.IsExam) { cellText += "Экзамен"; } else { cellText += "Консультация"; } cellText += Environment.NewLine; cellText += evt.DisciplineName + Environment.NewLine; cellText += evt.TeacherFIO + Environment.NewLine; cellText += evt.Time.ToString("H:mm") + Environment.NewLine; cellText += evt.Auditorium; oPara1 = oDoc.Content.Paragraphs.Add(timeTable.Cell(i + 1, 1).Range); oPara1.Range.Font.Size = 10; oPara1.Format.SpaceAfter = 0; oPara1.Range.Text = cellText; if (i != eventCount - 1) { timeTable.Cell(i + 1, 1).Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].Visible = true; } } } } } } oTable.Columns[1].Width = oWord.CentimetersToPoints(3); for (int i = 0; i < groups.Count; i++) { oTable.Columns[i + 2].Width = oWord.CentimetersToPoints(16 / groups.Count); } oTable.Rows.Alignment = Word.WdRowAlignment.wdAlignRowCenter; Word.Paragraph oPara2 = oDoc.Content.Paragraphs.Add(ref oMissing); oPara2.Range.Font.Size = 12; oPara2.Format.LineSpacing = oWord.LinesToPoints(1); oPara2.Range.Text = ""; oPara2.Format.SpaceAfter = 0; oPara2.Range.InsertParagraphAfter(); oPara2 = oDoc.Content.Paragraphs.Add(ref oMissing); oPara2.Range.Font.Size = 12; oPara2.Format.LineSpacing = oWord.LinesToPoints(1); oPara2.Range.Text = "Начальник учебного отдела\t\t" + "_________________ " + Constants.Constants.UchOtdHead; oPara2.Format.SpaceAfter = 0; oPara2.Range.InsertParagraphAfter(); oPara2.Range.InsertParagraphAfter(); oPara2 = oDoc.Content.Paragraphs.Add(ref oMissing); oPara2.Range.Font.Size = 12; oPara2.Format.LineSpacing = oWord.LinesToPoints(1); oPara2.Range.Text = "Декан " + Constants.Constants.facultyTitles[facCounter] + "\t\t_________________ " + Constants.Constants.HeadsOfFaculties.ElementAt(facCounter).Value; oPara2.Format.SpaceAfter = 0; oPara2.Range.InsertParagraphAfter(); oPara2.Range.InsertParagraphAfter(); if (facCounter != Constants.Constants.facultyGroups.Keys.Count - 1) { oDoc.Words.Last.InsertBreak(Word.WdBreakType.wdPageBreak); } Application.DoEvents(); } object fileName = Application.StartupPath + @"\Export2.docx"; //oDoc.SaveAs(ref fileName); //oWord.Quit(); }