//Methods public void Execute(ObservableCollection <object> parameters) { ParameterPayload = parameters; DateTime StartDate = (DateTime)ParameterPayload[0]; DateTime EndDate = (DateTime)ParameterPayload[1]; if (VerifyParameters()) { List <RecordSearch> recordSearches = _rss.GetRecordSearchesByCriteria(string.Format("WHERE DatePaid BETWEEN #{0}# AND #{1}# AND CheckNumber IS NOT NULL OR CheckNumber <> ''", StartDate.ToShortDateString(), EndDate.ToShortDateString())); try { Word.Application wordApp = new Word.Application { ShowAnimation = false, Visible = true }; missing = Missing.Value; document = wordApp.Documents.Add(ref missing, ref missing, ref missing, ref missing); document.Paragraphs.SpaceAfter = 0; AddTitle(StartDate, EndDate); //Create table Word.Paragraph tableSection = document.Content.Paragraphs.Add(ref missing); table = document.Tables.Add(tableSection.Range, recordSearches.Count + 1, 5, ref missing, ref missing); table.AllowAutoFit = true; table.AutoFitBehavior(Word.WdAutoFitBehavior.wdAutoFitWindow); SetColumnWidth(1, 15); SetColumnWidth(2, 15); SetColumnWidth(3, 45); SetColumnWidth(4, 15); SetColumnWidth(5, 10); //Create Header table.Rows[1].Borders[Word.WdBorderType.wdBorderBottom].LineStyle = Word.WdLineStyle.wdLineStyleSingle; table.Rows[1].Borders[Word.WdBorderType.wdBorderBottom].LineWidth = Word.WdLineWidth.wdLineWidth225pt; AddHeaderText(1, "Date Paid"); AddHeaderText(2, "IC File #"); AddHeaderText(3, "Project Name"); AddHeaderText(4, "Amount"); AddHeaderText(5, "Check #"); //Start Index at 2 to skip header row. int index = 2; foreach (RecordSearch rs in recordSearches) { AddEntry(index, rs); index++; } } catch (Exception exception) { MessageBox.Show(exception.Message); } } }
public static void FormatTable() { Word.Application app = Globals.ThisAddIn.Application; Word.Table table = app.Selection.Range.Tables[1]; for (int row = 1; row <= table.Rows.Count; row++) { for (int col = 1; col <= table.Columns.Count; col++) { try { table.Cell(row, col).Range.Select(); app.Selection.ClearFormatting(); if (row == 1) { table.Cell(row, col).Range.set_Style(app.ActiveDocument.Styles["2016_TableHeader | 10pt bold"]); } else { table.Cell(row, col).Range.set_Style(app.ActiveDocument.Styles["2016_Table | 9pt"]); } } catch (Exception f) { Debug.Print(f.Message); } } } table.set_Style(app.ActiveDocument.Styles["MasterTable"]); table.AutoFitBehavior(Word.WdAutoFitBehavior.wdAutoFitContent); table.AutoFitBehavior(Word.WdAutoFitBehavior.wdAutoFitWindow); try { table.Cell(1, 1).Row.HeadingFormat = (int)Word.WdConstants.wdToggle; table.ApplyStyleHeadingRows = true; } catch (Exception) { }; }
public void TableCreateGenre(int row, int col, string[] header, Dictionary <string, double> dictionary) { Object start = 80; Object end = 81; word.Range wordrange = worddocument.Range(ref start, ref end); //wordrange.InsertBreak(word.WdBreakType.wdPageBreak); wordrange.Bold = 400; Object defaultTableBehavior = word.WdDefaultTableBehavior.wdWord9TableBehavior; Object autoFitBehavior = word.WdAutoFitBehavior.wdAutoFitWindow; word.Table wordtable = worddocument.Tables.Add(wordrange, row + 1, col, ref defaultTableBehavior, ref autoFitBehavior); for (int c = 1; c <= col; c++) { word.Range wordcellrange = worddocument.Tables[1].Cell(1, c).Range; wordcellrange.Text = header[c - 1]; } int cellCounter = 2; foreach (var genre in dictionary) { word.Range wordcellrange = worddocument.Tables[1].Cell(cellCounter, 1).Range; wordcellrange.Text = (cellCounter - 1).ToString(); wordcellrange = worddocument.Tables[1].Cell(cellCounter, 2).Range; wordcellrange.Text = genre.Key; wordcellrange = worddocument.Tables[1].Cell(cellCounter, 3).Range; wordcellrange.Text = genre.Value.ToString(); cellCounter++; } wordtable.AllowAutoFit = true; word.Column firstCol = wordtable.Columns[1]; firstCol.AutoFit(); Single firstColAutoWidth = firstCol.Width; wordtable.AutoFitBehavior(word.WdAutoFitBehavior.wdAutoFitWindow); firstCol.SetWidth(firstColAutoWidth, word.WdRulerStyle.wdAdjustFirstColumn); object rEnd = worddocument.Content.End; int rt = (int)rEnd; object rStart = rt - 1; word.Range picRange = worddocument.Range(ref rStart, ref rEnd); picRange.InlineShapes.AddPicture(@"C:\Users\acer\Desktop\Учеба\АИС\Graf.bmp"); }
private void wordAddCfgObjectTable <TCfgObj>( string[] queries, string[] headers, ICollection <TCfgObj> cfgObjects) where TCfgObj : ICfgObject { Word.Table table = wordAddTable(cfgObjects.Count + 1, queries.Length); Word.Shading headerShading = table.Rows[1].Shading; headerShading.Texture = Word.WdTextureIndex.wdTextureSolid; bool moveRight = false; foreach (string header in headers) { if (moveRight) { wordMoveToCellRight(); } else { moveRight = true; } word.Selection.TypeText(header); } foreach (ICfgObject cfgObject in cfgObjects) { foreach (string query in queries) { wordMoveToCellRight(); word.Selection.TypeText( CfgObjectUtil.Query(cfgObject, query).ToString()); } } table.AutoFitBehavior(Word.WdAutoFitBehavior.wdAutoFitContent); }
public void TableCreateBook(int row, int col, string[] header, List <Book> books) { Object start = 94; Object end = 95; word.Range wordrange = worddocument.Range(ref start, ref end); //wordrange.InsertBreak(word.WdBreakType.wdPageBreak); wordrange.Bold = 400; Object defaultTableBehavior = word.WdDefaultTableBehavior.wdWord9TableBehavior; Object autoFitBehavior = word.WdAutoFitBehavior.wdAutoFitWindow; word.Table wordtable = worddocument.Tables.Add(wordrange, row + 1, col, ref defaultTableBehavior, ref autoFitBehavior); for (int c = 1; c <= col; c++) { word.Range wordcellrange = worddocument.Tables[1].Cell(1, c).Range; wordcellrange.Text = header[c - 1]; } for (int i = 0; i < row; i++) { word.Range wordcellrange = worddocument.Tables[1].Cell(i + 2, 1).Range; wordcellrange.Text = $"{books[i].Name} ({books[i].Type})"; wordcellrange = worddocument.Tables[1].Cell(i + 2, 2).Range; wordcellrange.Text = books[i].LitresEstimate.ToString(); wordcellrange = worddocument.Tables[1].Cell(i + 2, 3).Range; wordcellrange.Text = books[i].Description; } wordtable.AllowAutoFit = true; word.Column firstCol = wordtable.Columns[2]; firstCol.AutoFit(); Single firstColAutoWidth = firstCol.Width; wordtable.AutoFitBehavior(word.WdAutoFitBehavior.wdAutoFitWindow); firstCol.SetWidth(firstColAutoWidth, word.WdRulerStyle.wdAdjustFirstColumn); }
protected void PasteTable(List <List <string> > data, string bookmark) { Word.Range range = _document.Bookmarks.get_Item(bookmark).Range; range.Text = ""; int rowsCount = data.Count; int colsCount = data[0].Count; Word.Table table = _document.Tables.Add(range, rowsCount, colsCount, ref missing, ref missing); table.Borders.Enable = 1; table.AllowAutoFit = true; table.AutoFitBehavior(Word.WdAutoFitBehavior.wdAutoFitContent); object styleTableText = "Table text"; for (int r = 0; r < rowsCount; r++) { Word.Row row = table.Rows[r + 1]; for (int c = 0; c < colsCount; c++) { Word.Cell cell = row.Cells[c + 1]; cell.Range.set_Style(ref styleTableText); //Header row if (cell.RowIndex == 1) { cell.Range.Text = data[r][c]; cell.Range.Font.Bold = 1; cell.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; cell.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; } //Data row else { cell.Range.Text = data[r][c]; } } } }
public static void WorkingHistoryMinMax(string satellite, string beam, string polarization, DateTime firstDateSet, DateTime secondDateSet) { string path = null; DateTime firstDate = new DateTime(firstDateSet.Year, firstDateSet.Month, 1); DateTime secondDate = new DateTime(secondDateSet.Year, secondDateSet.Month, 1); try { SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.Filter = "Word files (*.docx)|*.docx"; saveFileDialog1.Title = "Отчёт за период от " + firstDate.ToShortDateString() + " до " + secondDate.ToShortDateString(); saveFileDialog1.FileName = firstDate.ToShortDateString() + " - " + secondDate.ToShortDateString() + ".docx"; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { path = saveFileDialog1.FileName; } else { return; } } catch (Exception e) { MessageBoxTi.Show("Documentation.WorkingHistory " + e.Message); return; } Thread t = new Thread(delegate() { try { Supports.GetProfileForm().ChangeState(); object miss = System.Reflection.Missing.Value; word.Application app = null; app = new word.Application(); Thread.Sleep(1000); var doc = app.Documents.Add(); app.Visible = false; Thread.Sleep(1000); doc.PageSetup.TopMargin = 80; doc.PageSetup.BottomMargin = 50; doc.PageSetup.LeftMargin = 60; doc.PageSetup.RightMargin = 60; var par = doc.Paragraphs.Add(); par = doc.Paragraphs.Add(); par.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter; par.Range.Font.Name = "Times New Roman"; par.Range.Font.Size = 12; par.Range.Text = "История включений Спутника " + satellite + ", " + beam + " - диапазона, " + polarization + " - поляризации"; par = doc.Paragraphs.Add(); word.Table fTable = par.Range.Tables.Add(doc.Range(doc.Content.End - 1, doc.Content.End), 2, 3, DefaultTableBehavior: miss, AutoFitBehavior: miss); fTable.Borders.InsideLineStyle = word.WdLineStyle.wdLineStyleSingle; fTable.Borders.OutsideLineStyle = word.WdLineStyle.wdLineStyleSingle; fTable.Cell(1, 1).Range.Text = "Минимум"; fTable.Cell(1, 2).Range.Text = "Максимум"; fTable.Cell(1, 3).Range.Text = "Месяц"; fTable.Range.Font.Size = 10; par = doc.Paragraphs.Add(); par = doc.Paragraphs.Add(); fTable.Range.Bold = 0; par.Range.Font.Bold = 0; par = doc.Paragraphs.Add(); par = doc.Paragraphs.Add(); par.Range.Text = firstDate.ToString("dd/MM/yyyy"); par.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter; List <int> oneMonth = new List <int>(); int prevMonth = firstDate.Month; for (var i = 0; i < (secondDate.AddMonths(1) - firstDate).TotalDays; i++) { if (prevMonth == firstDate.AddDays(i).Month) { oneMonth.Add(Convert.ToInt32(dataBase.ToCount("SELECT ((SELECT COUNT(*) FROM SSALoading WHERE [Спутник] = '" + satellite + "' AND [Диапазон] = '" + beam + "' AND [Поляризация] = '" + polarization + "' AND [Состояние] = 0 AND[ВремяВкл] > '" + firstDate.Date.AddDays(i) + "' AND[ВремяВкл] < GETDATE()) - " + "(SELECT COUNT(*) FROM SSALoading WHERE [Спутник] = '" + satellite + "' AND [Диапазон] = '" + beam + "' AND [Поляризация] = '" + polarization + "' AND [Состояние] = 1 AND[ВремяВкл] > '" + firstDate.Date.AddDays(i) + "' AND[ВремяВкл] < GETDATE()) + " + "(SELECT COUNT(*) FROM Loading WHERE [Спутник] = '" + satellite + "' AND [Диапазон] = '" + beam + "' AND [Поляризация] = '" + polarization + "' AND [Состояние] = 1)) as [ALL]"))); } else { fTable.Cell(fTable.Rows.Count, 1).Range.Text = oneMonth.Min().ToString(); fTable.Cell(fTable.Rows.Count, 2).Range.Text = oneMonth.Max().ToString(); fTable.Cell(fTable.Rows.Count, 3).Range.Text = firstDate.AddDays(i).ToString("MM/yyyy"); fTable.Range.Rows.Add(); oneMonth.Clear(); oneMonth.Add(Convert.ToInt32(dataBase.ToCount("SELECT ((SELECT COUNT(*) FROM SSALoading WHERE [Спутник] = '" + satellite + "' AND [Диапазон] = '" + beam + "' AND [Поляризация] = '" + polarization + "' AND [Состояние] = 0 AND[ВремяВкл] > '" + firstDate.Date.AddDays(i) + "' AND[ВремяВкл] < GETDATE()) - " + "(SELECT COUNT(*) FROM SSALoading WHERE [Спутник] = '" + satellite + "' AND [Диапазон] = '" + beam + "' AND [Поляризация] = '" + polarization + "' AND [Состояние] = 1 AND[ВремяВкл] > '" + firstDate.Date.AddDays(i) + "' AND[ВремяВкл] < GETDATE()) + " + "(SELECT COUNT(*) FROM Loading WHERE [Спутник] = '" + satellite + "' AND [Диапазон] = '" + beam + "' AND [Поляризация] = '" + polarization + "' AND [Состояние] = 1)) as [ALL]"))); } prevMonth = firstDate.AddDays(i).Month; } fTable.Range.Rows[fTable.Range.Rows.Count].Delete(); fTable.Range.Paragraphs.SpaceAfter = 0; fTable.Columns[1].Width = 60; fTable.Columns[1].Width = 60; fTable.Columns[1].Width = 60; fTable.Columns[1].Width = 60; fTable.AutoFitBehavior(word.WdAutoFitBehavior.wdAutoFitWindow); fTable.Range.ParagraphFormat.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter; app.ActiveDocument.SaveAs(path, word.WdSaveFormat.wdFormatDocumentDefault); doc.Close(); MessageBoxTi.Show("Отчёт готов"); if (app != null) { app.Quit(); Marshal.FinalReleaseComObject(app); Thread.CurrentThread.Abort(); } Thread.CurrentThread.Abort(); } catch (Exception e) { if (e.GetType() != typeof(ThreadAbortException)) { MessageBoxTi.Show("Documentation.WorkingHistory.Thread " + e.Message); } return; } finally { Supports.GetProfileForm().ChangeState(true); } }); t.Start(); }
/// <summary> /// Отчёт для 203 поста /// </summary> /// <param name="date"> /// Дата, для которой нужно расчитать /// </param> /// <param name="days"> /// Если не 0, то расчитывается для периода с той даты которая указана + это количество дней /// </param> public static void TillCalledFor203Report(DateTime date, int days = 0) { string path = null; System.Data.DataTable dt = dataBase.SimpleData("Loading WHERE [Спутник] = 'Кореасат-5' AND [Состояние] = 'true' AND [Диапазон] = 'Ku' AND [Примечание] LIKE '%AIS%'"); try { SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.Filter = "Word files (*.docx)|*.docx"; saveFileDialog1.Title = days == 0 ? "Отчёт за " + date.ToShortDateString() : "Отчёт за период от " + date.ToShortDateString() + " до " + date.AddDays(days).ToShortDateString(); saveFileDialog1.FileName = days == 0 ? date.ToShortDateString() + ".docx" : date.ToShortDateString() + " - " + date.AddDays(days).ToShortDateString() + ".docx"; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { path = saveFileDialog1.FileName; } else { return; } } catch (Exception e) { MessageBoxTi.Show("Documentation.TillCalledFor203Report " + e.Message); return; } Thread t = new Thread(delegate() { try { Supports.GetProfileForm().ChangeState(); object miss = System.Reflection.Missing.Value; word.Application app = null; app = new word.Application(); Thread.Sleep(1000); var doc = app.Documents.Add(); app.Visible = false; Thread.Sleep(1000); doc.PageSetup.TopMargin = 80; doc.PageSetup.BottomMargin = 50; doc.PageSetup.LeftMargin = 60; doc.PageSetup.RightMargin = 60; var par = doc.Paragraphs.Add(); par.Range.Text = "Доклад 203 БП"; par.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter; par.Range.Font.Name = "Times New Roman"; par.Range.Font.Size = 12; par = doc.Paragraphs.Add(); par = doc.Paragraphs.Add(); par.Range.Text = "1. Статистика:"; par = doc.Paragraphs.Add(); par = doc.Paragraphs.Add(); string firDate = days == 0 ? (date.AddDays(-1) + new TimeSpan(9, 0, 0)).ToString() : (date + new TimeSpan(9, 0, 0)).ToString(); string secDate = days == 0 ? (date + new TimeSpan(9, 0, 0)).ToString() : (date + new TimeSpan(9, 0, 0)).AddDays(days).ToString(); par.Range.Text = "Включилось:" + dataBase.ToCount("SELECT COUNT(*) FROM SSALoading WHERE [Спутник] = 'Кореасат-5' AND [ВремяВкл] > '" + firDate + "' AND [ВремяВкл] < '" + secDate + "' AND [Состояние] = '1' AND [Диапазон] = 'Ku'").ToString(); par.Alignment = word.WdParagraphAlignment.wdAlignParagraphLeft; par = doc.Paragraphs.Add(); par = doc.Paragraphs.Add(); par.Range.Text = "Выключилось:" + dataBase.ToCount("SELECT COUNT(*) FROM SSALoading WHERE [Спутник] = 'Кореасат-5' AND [ВремяВкл] > '" + firDate + "' AND [ВремяВкл] < '" + secDate + "' AND [Состояние] = '0' AND [Диапазон] = 'Ku'").ToString(); par.Alignment = word.WdParagraphAlignment.wdAlignParagraphLeft; par = doc.Paragraphs.Add(); par = doc.Paragraphs.Add(); par.Range.Text = "2. Номиналы включённых излучений:"; par = doc.Paragraphs.Add(); word.Table fTable = par.Range.Tables.Add(doc.Range(doc.Content.End - 1, doc.Content.End), 2, 4, DefaultTableBehavior: miss, AutoFitBehavior: miss); fTable.Borders.InsideLineStyle = word.WdLineStyle.wdLineStyleSingle; fTable.Borders.OutsideLineStyle = word.WdLineStyle.wdLineStyleSingle; fTable.Cell(1, 1).Range.Text = "Частота"; fTable.Cell(1, 2).Range.Text = "Стек протоков"; fTable.Cell(1, 3).Range.Text = "Время"; fTable.Cell(1, 4).Range.Text = "Примечание"; fTable.Range.Font.Size = 10; par = doc.Paragraphs.Add(); par = doc.Paragraphs.Add(); fTable.Range.Bold = 0; par.Range.Font.Bold = 0; par = doc.Paragraphs.Add(); par = doc.Paragraphs.Add(); par.Range.Text = date.ToString("dd/MM/yyyy"); par.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter; foreach (DataRow dr in dt.Rows.Cast <DataRow>()) { fTable.Cell(fTable.Rows.Count, 1).Range.Text = dr["Частота"].ToString(); fTable.Cell(fTable.Rows.Count, 2).Range.Text = dr["СтекПрот"].ToString(); fTable.Cell(fTable.Rows.Count, 3).Range.Text = dr["ВремяДоб"].ToString(); fTable.Cell(fTable.Rows.Count, 4).Range.Text = dr["Примечание"].ToString(); fTable.Range.Rows.Add(); } fTable.Range.Rows[fTable.Range.Rows.Count].Delete(); fTable.Range.Paragraphs.SpaceAfter = 0; fTable.Columns[1].Width = 60; fTable.Columns[1].Width = 60; fTable.Columns[1].Width = 60; fTable.Columns[1].Width = 60; fTable.AutoFitBehavior(word.WdAutoFitBehavior.wdAutoFitWindow); fTable.Range.ParagraphFormat.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter; app.ActiveDocument.SaveAs(path, word.WdSaveFormat.wdFormatDocumentDefault); doc.Close(); MessageBoxTi.Show("Отчёт готов"); if (app != null) { app.Quit(); Marshal.FinalReleaseComObject(app); Thread.CurrentThread.Abort(); } Thread.CurrentThread.Abort(); } catch (Exception e) { if (e.GetType() != typeof(ThreadAbortException)) { MessageBoxTi.Show("Documentation.TillCalledFor203Report.Thread " + e.Message); } return; } finally { Supports.GetProfileForm().ChangeState(true); } }); t.Start(); }
/// <summary> /// Ежедневный отчёт для 202 поста, выгружается в Word /// </summary> /// <param name="date"> /// Дата, для которой нужно расчитать /// </param> /// <param name="days"> /// Если не 0, то расчитывается для периода с той даты которая указана + это количество дней /// </param> public static void Daily202Report(DateTime date, int days = 0) { string path = null; try { SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.Filter = "Word files (*.docx)|*.docx"; saveFileDialog1.Title = days == 0 ? "Отчёт за " + date.ToShortDateString() : "Отчёт за период от " + date.ToShortDateString() + " до " + date.AddDays(days).ToShortDateString(); saveFileDialog1.FileName = days == 0 ? date.ToShortDateString() + ".docx" : date.ToShortDateString() + " - " + date.AddDays(days).ToShortDateString() + ".docx"; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { path = saveFileDialog1.FileName; } else { return; } } catch (Exception e) { MessageBoxTi.Show("Documentation.Daily202Report " + e.Message); return; } Thread t = new Thread(delegate() { try { Supports.GetProfileForm().ChangeState(); object miss = System.Reflection.Missing.Value; word.Application app = null; System.Data.DataTable dt = dataBase.SimpleData("[dbo].[MainSettings] left join [dbo].[SatelliteList] ON [dbo].[MainSettings].[Content] = [dbo].[SatelliteList].[НаименованиеИСЗ] WHERE [dbo].[MainSettings].[What] = 'NS2DocumentationCheckedListBox' OR [dbo].[MainSettings].[What] = 'NS2DocumentationCheckedListBox1'"); if (dt.Rows.Cast <DataRow>().Where(x => x["What"].ToString() == "NS2DocumentationCheckedListBox").Count() == 0) { MessageBoxTi.Show("Упс, не выбран ни один спутник, сообщите НС о данной ошибке"); return; } app = new word.Application(); Thread.Sleep(1000); var doc = app.Documents.Add(); app.Visible = false; Thread.Sleep(1000); doc.PageSetup.Orientation = word.WdOrientation.wdOrientLandscape; doc.PageSetup.TopMargin = 80; doc.PageSetup.BottomMargin = 50; doc.PageSetup.LeftMargin = 60; doc.PageSetup.RightMargin = 60; var par = doc.Paragraphs.Add(); par.Range.Text = "Доклад 202 БП"; par.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter; par.Range.Font.Name = "Times New Roman"; par.Range.Font.Size = 12; par = doc.Paragraphs.Add(); par = doc.Paragraphs.Add(); System.Data.DataTable MainSettings = dataBase.SimpleData("MainSettings"); if (MainSettings.Select().Where(x => x["What"].ToString() == "NS2DocumentationTextBox").Where(x => x["Who"].ToString() == "SatelliteForDailyReport").Count() != 0) { par.Range.Text = MainSettings.Select().Where(x => x["What"].ToString() == "NS2DocumentationTextBox").Where(x => x["Who"].ToString() == "SatelliteForDailyReport").FirstOrDefault()["Content"].ToString(); } else { par.Range.Text = "1. Изменения в ВЧ загрузке ССС МО США ДСЦС и ВГС, ССС МО Великобритании СКАЙНЕТ:"; } par.Alignment = word.WdParagraphAlignment.wdAlignParagraphLeft; par.Range.Font.Bold = 1; par = doc.Paragraphs.Add(); word.Table fTable = par.Range.Tables.Add(doc.Range(doc.Content.End - 1, doc.Content.End), 4, 13, DefaultTableBehavior: miss, AutoFitBehavior: miss); fTable.Borders.InsideLineStyle = word.WdLineStyle.wdLineStyleSingle; fTable.Borders.OutsideLineStyle = word.WdLineStyle.wdLineStyleSingle; fTable.Cell(1, 1).Merge(fTable.Cell(3, 1)); fTable.Cell(1, 2).Merge(fTable.Cell(3, 2)); fTable.Cell(1, 3).Merge(fTable.Cell(3, 3)); fTable.Cell(1, 4).Merge(fTable.Cell(1, 8)); fTable.Cell(1, 5).Merge(fTable.Cell(1, 9)); fTable.Cell(2, 4).Merge(fTable.Cell(3, 4)); fTable.Cell(2, 5).Merge(fTable.Cell(3, 5)); fTable.Cell(2, 6).Merge(fTable.Cell(2, 8)); fTable.Cell(2, 7).Merge(fTable.Cell(2, 8)); fTable.Cell(2, 8).Merge(fTable.Cell(2, 9)); fTable.Cell(2, 9).Merge(fTable.Cell(3, 13)); fTable.Cell(1, 1).Range.Text = "Наименование ИСЗ"; fTable.Cell(1, 2).Range.Text = "Межд. Номер"; fTable.Cell(1, 3).Range.Text = "ПСТ"; fTable.Cell(1, 4).Range.Text = "Излучений"; fTable.Cell(1, 5).Range.Text = "Излучений по системам"; fTable.Cell(2, 4).Range.Text = "вкл."; fTable.Cell(2, 5).Range.Text = "выкл."; fTable.Cell(2, 6).Range.Text = "Всего"; fTable.Cell(2, 7).Range.Text = "ОКС"; fTable.Cell(2, 8).Range.Text = "Вин-Т"; fTable.Cell(2, 9).Range.Text = "ГБС"; fTable.Cell(3, 6).Range.Text = "X"; fTable.Cell(3, 7).Range.Text = "Ka"; fTable.Cell(3, 8).Range.Text = "∑"; fTable.Cell(3, 9).Range.Text = "ПДКП"; fTable.Cell(3, 10).Range.Text = "ДТС"; fTable.Cell(3, 11).Range.Text = "МДЧР"; fTable.Cell(3, 12).Range.Text = "МДВР"; fTable.Range.Font.Size = 10; par = doc.Paragraphs.Add(); par = doc.Paragraphs.Add(); if (MainSettings.Select().Where(x => x["What"].ToString() == "NS2DocumentationTextBox1").Where(x => x["Who"].ToString() == "SatelliteForDailyReport").Count() != 0) { par.Range.Text = MainSettings.Select().Where(x => x["What"].ToString() == "NS2DocumentationTextBox1").Where(x => x["Who"].ToString() == "SatelliteForDailyReport").FirstOrDefault()["Content"].ToString(); } else { par.Range.Text = "2. Изменения в ВЧ загрузке геостационарных ИСЗ связи:"; } par = doc.Paragraphs.Add(); word.Table sTable = par.Range.Tables.Add(doc.Range(doc.Content.End - 1, doc.Content.End), 3, 6, DefaultTableBehavior: miss, AutoFitBehavior: miss); sTable.Cell(1, 1).Merge(sTable.Cell(2, 1)); sTable.Cell(1, 2).Merge(sTable.Cell(2, 2)); sTable.Cell(1, 3).Merge(sTable.Cell(2, 3)); sTable.Cell(1, 4).Merge(sTable.Cell(1, 6)); sTable.Cell(1, 1).Range.Text = "Наименование ИСЗ"; sTable.Cell(1, 2).Range.Text = "Межд. Номер"; sTable.Cell(1, 3).Range.Text = "ПСТ"; sTable.Cell(1, 4).Range.Text = "Излучений"; sTable.Cell(2, 4).Range.Text = "вкл."; sTable.Cell(2, 5).Range.Text = "выкл."; sTable.Cell(2, 6).Range.Text = "Всего"; sTable.Range.Font.Size = 10; sTable.Borders.InsideLineStyle = word.WdLineStyle.wdLineStyleSingle; sTable.Borders.OutsideLineStyle = word.WdLineStyle.wdLineStyleSingle; par = doc.Paragraphs.Add(); par = doc.Paragraphs.Add(); if (MainSettings.Select().Where(x => x["What"].ToString() == "NS2DocumentationTextBox2").Where(x => x["Who"].ToString() == "SatelliteForDailyReport").Count() != 0) { par.Range.Text = MainSettings.Select().Where(x => x["What"].ToString() == "NS2DocumentationTextBox2").Where(x => x["Who"].ToString() == "SatelliteForDailyReport").FirstOrDefault()["Content"].ToString(); } else { par.Range.Text = "3. Причины изменений в ВЧ загрузке ССС МО США ВГС не отмечено"; } par = doc.Paragraphs.Add(); par = doc.Paragraphs.Add(); par.Range.Text = "Оператор: " + Profile.userName; par.Range.Font.Bold = 0; par = doc.Paragraphs.Add(); par = doc.Paragraphs.Add(); par.Range.Text = date.ToString("dd/MM/yyyy"); par.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter; var j = 0; string firDate = days == 0 ? (date.AddDays(-1) + new TimeSpan(9, 0, 0)).ToString() : (date + new TimeSpan(9, 0, 0)).ToString(); string secDate = days == 0 ? (date + new TimeSpan(9, 0, 0)).ToString() : (date + new TimeSpan(9, 0, 0)).AddDays(days).ToString(); fTable.Range.Bold = 0; var n = dt.Rows.Cast <DataRow>().Where(x => x["What"].ToString() == "NS2DocumentationCheckedListBox").Count(); foreach (DataRow dr in dt.Rows.Cast <DataRow>().Where(x => x["What"].ToString() == "NS2DocumentationCheckedListBox").OrderBy(x => x["НаименованиеИСЗ"])) { fTable.Cell(fTable.Rows.Count, 1).Range.Text = dr["НаименованиеИСЗ"].ToString(); fTable.Cell(fTable.Rows.Count, 2).Range.Text = dr["МеждНомер"].ToString(); fTable.Cell(fTable.Rows.Count, 3).Range.Text = dr["ПСТ"].ToString(); fTable.Cell(fTable.Rows.Count, 4).Range.Text = dataBase.ToCount("SELECT COUNT(*) FROM SSALoading WHERE [Спутник] = '" + dr["НаименованиеИСЗ"].ToString() + "' AND [ВремяВкл] > '" + firDate + "' AND [ВремяВкл] < '" + secDate + "' AND [Состояние] = '1'").ToString(); fTable.Cell(fTable.Rows.Count, 5).Range.Text = dataBase.ToCount("SELECT COUNT(*) FROM SSALoading WHERE [Спутник] = '" + dr["НаименованиеИСЗ"].ToString() + "' AND [ВремяВкл] > '" + firDate + "' AND [ВремяВкл] < '" + secDate + "' AND [Состояние] = '0'").ToString(); fTable.Cell(fTable.Rows.Count, 6).Range.Text = dataBase.ToCount("SELECT COUNT(*) FROM Loading WHERE [Спутник] = '" + dr["НаименованиеИСЗ"].ToString() + "' AND [Диапазон] = 'X' AND [Состояние] = 'true'").ToString(); fTable.Cell(fTable.Rows.Count, 7).Range.Text = dataBase.ToCount("SELECT COUNT(*) FROM Loading WHERE [Спутник] = '" + dr["НаименованиеИСЗ"].ToString() + "' AND [Диапазон] = 'Ka' AND [Состояние] = 'true'").ToString(); fTable.Cell(fTable.Rows.Count, 8).Range.Text = (Convert.ToInt32(fTable.Cell(fTable.Rows.Count, 6).Range.Text.Replace("\r\a", string.Empty)) + Convert.ToInt32(fTable.Cell(fTable.Rows.Count, 7).Range.Text.Replace("\r\a", string.Empty))).ToString(); fTable.Cell(fTable.Rows.Count, 9).Range.Text = dataBase.ToCount("SELECT COUNT(*) FROM Loading WHERE [Спутник] = '" + dr["НаименованиеИСЗ"].ToString() + "' AND ([Диапазон] = 'Ka' OR [Диапазон] = 'X') AND [СистемаСвязи] != 'WIN-T' AND [ТипДанных] = 'ПДКП' AND [Состояние] = 1").ToString(); fTable.Cell(fTable.Rows.Count, 10).Range.Text = dataBase.ToCount("SELECT COUNT(*) FROM Loading WHERE [Спутник] = '" + dr["НаименованиеИСЗ"].ToString() + "' AND ([Диапазон] = 'Ka' OR [Диапазон] = 'X') AND [СистемаСвязи] = 'DTS' AND [Состояние] = 1").ToString(); fTable.Cell(fTable.Rows.Count, 11).Range.Text = dataBase.ToCount("SELECT COUNT(*) FROM Loading WHERE [Спутник] = '" + dr["НаименованиеИСЗ"].ToString() + "' AND [Диапазон] = 'Ka' AND [Состояние] = 'true' AND (([Тактовая] > '2729' AND [Тактовая] < '2731') OR ([Тактовая] > '3071' AND [Тактовая] < '3073'))").ToString(); fTable.Cell(fTable.Rows.Count, 12).Range.Text = dataBase.ToCount("SELECT COUNT(*) FROM Loading WHERE [Спутник] = '" + dr["НаименованиеИСЗ"].ToString() + "' AND [Диапазон] = 'Ka' AND [Состояние] = 'true' AND[ВидДоступа] = 'МДВР'").ToString(); fTable.Cell(fTable.Rows.Count, 13).Range.Text = dataBase.ToCount("SELECT COUNT(*) FROM Loading WHERE [Спутник] = '" + dr["НаименованиеИСЗ"].ToString() + "' AND ([Диапазон] = 'Ka' OR [Диапазон] = 'X') AND [СистемаСвязи] = 'GBS'").ToString(); j++; if (j < n) { fTable.Rows.Add(); } } j = 0; n = dt.Rows.Cast <DataRow>().Where(x => x["What"].ToString() == "NS2DocumentationCheckedListBox1").Count(); if (dt.Rows.Cast <DataRow>().Where(x => x["What"].ToString() == "NS2DocumentationCheckedListBox1").Count() != 0) { foreach (DataRow dr in dt.Rows.Cast <DataRow>().Where(x => x["What"].ToString() == "NS2DocumentationCheckedListBox1").OrderBy(x => x["НаименованиеИСЗ"])) { sTable.Cell(sTable.Rows.Count, 1).Range.Text = dr["НаименованиеИСЗ"].ToString(); sTable.Cell(sTable.Rows.Count, 2).Range.Text = dr["МеждНомер"].ToString(); sTable.Cell(sTable.Rows.Count, 3).Range.Text = dr["ПСТ"].ToString(); sTable.Cell(sTable.Rows.Count, 4).Range.Text = dataBase.ToCount("SELECT COUNT(*) FROM SSALoading WHERE [Спутник] = '" + dr["НаименованиеИСЗ"].ToString() + "' AND [ВремяВкл] > '" + firDate + "' AND [ВремяВкл] < '" + secDate + "' AND [Состояние] = '1' AND ([Диапазон] = 'Ka' OR [Диапазон] = 'X')").ToString(); sTable.Cell(sTable.Rows.Count, 5).Range.Text = dataBase.ToCount("SELECT COUNT(*) FROM SSALoading WHERE [Спутник] = '" + dr["НаименованиеИСЗ"].ToString() + "' AND [ВремяВкл] > '" + firDate + "' AND [ВремяВкл] < '" + secDate + "' AND [Состояние] = '0' AND ([Диапазон] = 'Ka' OR [Диапазон] = 'X')").ToString(); sTable.Cell(sTable.Rows.Count, 6).Range.Text = dataBase.ToCount("SELECT COUNT(*) FROM Loading WHERE [Спутник] = '" + dr["НаименованиеИСЗ"].ToString() + "' AND [Состояние] = 'true' AND ([Диапазон] = 'X' OR [Диапазон] = 'Ka')").ToString(); j++; if (j < n) { sTable.Rows.Add(); } } } fTable.Range.Paragraphs.SpaceAfter = 0; sTable.Range.Paragraphs.SpaceAfter = 0; fTable.Cell(1, 3).Width = 60; for (var i = 4; i <= fTable.Rows.Count; i++) { fTable.Cell(i, 3).Width = 60; } fTable.Cell(1, 2).Width = 50; for (var i = 4; i <= fTable.Rows.Count; i++) { fTable.Cell(i, 2).Width = 50; } fTable.AutoFitBehavior(word.WdAutoFitBehavior.wdAutoFitWindow); sTable.AutoFitBehavior(word.WdAutoFitBehavior.wdAutoFitWindow); fTable.Range.ParagraphFormat.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter; sTable.Range.ParagraphFormat.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter; app.ActiveDocument.SaveAs(path, word.WdSaveFormat.wdFormatDocumentDefault); doc.Close(); MessageBoxTi.Show("Отчёт готов"); if (app != null) { app.Quit(); Marshal.FinalReleaseComObject(app); Thread.CurrentThread.Abort(); } } catch (Exception e) { if (e.GetType() != typeof(ThreadAbortException)) { MessageBoxTi.Show("Documentation.Daily202Report.Thread " + e.Message); } return; } finally { Supports.GetProfileForm().ChangeState(true); } }); t.Start(); }
public bool gen_report() { //初始 MSWord.Document doc = null; MSWord.Application wordApp = new MSWord.Application(); object missing = null; MSWord.Table table = null; MSWord.Table sub_table = null; string tuhao = ""; string jyxm = ""; try { doc = wordApp.Documents.Open(this.f2_muban_path); } //System.Reflection.Missing.Value catch { } table = doc.Tables[1]; //判断此叶片编号在不合格列表中是否存在 for (int i = 0; i < hege.Count; i++) { for (int j = 0; j < buhege.Count; j++) { if (Regex.IsMatch(hege[i], buhege[j])) { break; } if (j == buhege.Count - 1) { hege1.Add(hege[i]); } } } //基表格的遍历 for (int tabel_cnt = 1; tabel_cnt <= doc.Tables.Count; tabel_cnt++) { //表格内容遍历 for (int i = 1; i <= table.Rows.Count; i++) { for (int j = 1; j <= table.Columns.Count; j++) { //因为每一行的列数并不确定,当访问不存在的cell时会报错,所以使用try-catch try { //填入 零件数量 if (table.Cell(i, j).Range.Text.ToString() == "零件数量\r\a") { table.Cell(i, j + 1).Range.Text = (buhege.Count + hege1.Count).ToString() + "件."; } //读取 零件图号 if (table.Cell(i, j).Range.Text.ToString() == "零件图号\r\a") { tuhao = table.Cell(i, j + 1).Range.Text; tuhao = tuhao.Split(new string[] { "\r\a" }, StringSplitOptions.RemoveEmptyEntries)[0]; try { string[] a = tuhao.Split(new string[] { "\r" }, StringSplitOptions.RemoveEmptyEntries); tuhao = ""; foreach (string b in a) { tuhao += b; } } catch { } } //读取 检验项目 if (table.Cell(i, j).Range.Text.ToString() == "检验项目\r\a") { jyxm = table.Cell(i, j + 1).Range.Text.Split(new string[] { "\r\a" }, StringSplitOptions.RemoveEmptyEntries)[0]; } //寻找 报告内容 if (Regex.IsMatch(table.Cell(i, j).Range.Text.ToString(), "报告内容:")) { int add_rows = 0; //首先写入 合格报告 if (hege1.Count > 0) { //换行 table.Cell(i, j).Range.InsertAfter("\r\n"); // table.Cell(i, j).Range.InsertAfter("经三坐标检测,共" + hege1.Count.ToString() + "件精铸件" + jyxm + "符合图样" + tuhao + "的要求,为合格件\r\n"); object what = MSWord.WdUnits.wdLine; object count = 14; object dummy = System.Reflection.Missing.Value; wordApp.Selection.MoveDown(what, count); sub_table = doc.Tables.Add(wordApp.Selection.Range, 2, 8); sub_table.AutoFitBehavior(MSWord.WdAutoFitBehavior.wdAutoFitWindow); //写入表头 sub_table.Cell(1, 1).Range.Text = "序号"; sub_table.Cell(1, 2).Range.Text = "编号"; sub_table.Cell(1, 3).Range.Text = "序号"; sub_table.Cell(1, 4).Range.Text = "编号"; sub_table.Cell(1, 5).Range.Text = "序号"; sub_table.Cell(1, 6).Range.Text = "编号"; sub_table.Cell(1, 7).Range.Text = "序号"; sub_table.Cell(1, 8).Range.Text = "编号"; sub_table.Borders.OutsideLineStyle = MSWord.WdLineStyle.wdLineStyleSingle; sub_table.Borders.OutsideLineWidth = table.Borders.OutsideLineWidth; sub_table.Borders.InsideLineStyle = MSWord.WdLineStyle.wdLineStyleSingle; sub_table.Borders.InsideLineWidth = table.Borders.InsideLineWidth; sub_table.Cell(1, 1).Width = sub_table.Cell(1, 1).Width * 2f / 3f; sub_table.Cell(1, 2).Width = sub_table.Cell(1, 2).Width * 4f / 3f; sub_table.Cell(1, 3).Width = sub_table.Cell(1, 3).Width * 2f / 3f; sub_table.Cell(1, 4).Width = sub_table.Cell(1, 4).Width * 4f / 3f; sub_table.Cell(1, 5).Width = sub_table.Cell(1, 5).Width * 2f / 3f; sub_table.Cell(1, 6).Width = sub_table.Cell(1, 6).Width * 4f / 3f; sub_table.Cell(1, 7).Width = sub_table.Cell(1, 7).Width * 2f / 3f; sub_table.Cell(1, 8).Width = sub_table.Cell(1, 8).Width * 4f / 3f; sub_table.Cell(2, 1).Width = sub_table.Cell(2, 1).Width * 2f / 3f; sub_table.Cell(2, 2).Width = sub_table.Cell(2, 2).Width * 4f / 3f; sub_table.Cell(2, 3).Width = sub_table.Cell(2, 3).Width * 2f / 3f; sub_table.Cell(2, 4).Width = sub_table.Cell(2, 4).Width * 4f / 3f; sub_table.Cell(2, 5).Width = sub_table.Cell(2, 5).Width * 2f / 3f; sub_table.Cell(2, 6).Width = sub_table.Cell(2, 6).Width * 4f / 3f; sub_table.Cell(2, 7).Width = sub_table.Cell(2, 7).Width * 2f / 3f; sub_table.Cell(2, 8).Width = sub_table.Cell(2, 8).Width * 4f / 3f; int rows = hege1.Count / 4; add_rows = rows + 1; for (int m = 0; m < rows; m++) { sub_table.Rows.Add(sub_table.Cell(table.Rows.Count, 1)); } int jj = 1; int ii = 2; for (int m = 0; m < hege1.Count; m++) { sub_table.Cell(ii, jj).Range.Text = (m + 1).ToString(); sub_table.Cell(ii, jj + 1).Range.Text = hege1[m].ToString(); if (ii == rows + 2) { jj += 2; ii = 2; } else { ii++; } } } //之后写入 不合格 if (buhege.Count > 0) { table.Cell(i, j).Range.InsertAfter("经三坐标检测,共" + buhege.Count.ToString() + "件精铸件" + jyxm + "不符合图样" + tuhao + "的要求,为不合格件\r\n"); //table.Cell(i, j).Range.Font.Spacing = table.Cell(i-1, 1).Range.Font.Spacing; object what = MSWord.WdUnits.wdLine; object count = 4 + add_rows; object dummy = System.Reflection.Missing.Value; wordApp.Selection.MoveDown(what, count); sub_table = doc.Tables.Add(wordApp.Selection.Range, 2, 8); sub_table.AutoFitBehavior(MSWord.WdAutoFitBehavior.wdAutoFitWindow); //写入表头 sub_table.Cell(1, 1).Range.Text = "序号"; sub_table.Cell(1, 2).Range.Text = "编号"; sub_table.Cell(1, 3).Range.Text = "序号"; sub_table.Cell(1, 4).Range.Text = "编号"; sub_table.Cell(1, 5).Range.Text = "序号"; sub_table.Cell(1, 6).Range.Text = "编号"; sub_table.Cell(1, 7).Range.Text = "序号"; sub_table.Cell(1, 8).Range.Text = "编号"; sub_table.Borders.OutsideLineStyle = MSWord.WdLineStyle.wdLineStyleSingle; sub_table.Borders.OutsideLineWidth = table.Borders.OutsideLineWidth; sub_table.Borders.InsideLineStyle = MSWord.WdLineStyle.wdLineStyleSingle; sub_table.Borders.InsideLineWidth = table.Borders.InsideLineWidth; sub_table.Cell(1, 1).Width = sub_table.Cell(1, 1).Width * 2f / 3f; sub_table.Cell(1, 2).Width = sub_table.Cell(1, 2).Width * 4f / 3f; sub_table.Cell(1, 3).Width = sub_table.Cell(1, 3).Width * 2f / 3f; sub_table.Cell(1, 4).Width = sub_table.Cell(1, 4).Width * 4f / 3f; sub_table.Cell(1, 5).Width = sub_table.Cell(1, 5).Width * 2f / 3f; sub_table.Cell(1, 6).Width = sub_table.Cell(1, 6).Width * 4f / 3f; sub_table.Cell(1, 7).Width = sub_table.Cell(1, 7).Width * 2f / 3f; sub_table.Cell(1, 8).Width = sub_table.Cell(1, 8).Width * 4f / 3f; sub_table.Cell(2, 1).Width = sub_table.Cell(2, 1).Width * 2f / 3f; sub_table.Cell(2, 2).Width = sub_table.Cell(2, 2).Width * 4f / 3f; sub_table.Cell(2, 3).Width = sub_table.Cell(2, 3).Width * 2f / 3f; sub_table.Cell(2, 4).Width = sub_table.Cell(2, 4).Width * 4f / 3f; sub_table.Cell(2, 5).Width = sub_table.Cell(2, 5).Width * 2f / 3f; sub_table.Cell(2, 6).Width = sub_table.Cell(2, 6).Width * 4f / 3f; sub_table.Cell(2, 7).Width = sub_table.Cell(2, 7).Width * 2f / 3f; sub_table.Cell(2, 8).Width = sub_table.Cell(2, 8).Width * 4f / 3f; int rows = buhege.Count / 4; for (int m = 0; m < rows; m++) { sub_table.Rows.Add(sub_table.Cell(table.Rows.Count, 1)); } int jj = 1; int ii = 2; for (int m = 0; m < buhege.Count; m++) { sub_table.Cell(ii, jj).Range.Text = (m + 1).ToString(); sub_table.Cell(ii, jj + 1).Range.Text = buhege[m].ToString(); if (ii == rows + 2) { jj += 2; ii = 2; } else { ii++; } } } } } catch { } } } } //文档编辑完以后必须要保存,否则更改无效! string path = f2_save_path + "\\" + "检验报告" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Day.ToString() + "-" + DateTime.Now.Hour.ToString() + "-" + DateTime.Now.Minute.ToString(); doc.SaveAs(@path); doc.Close(ref missing, ref missing, ref missing); this.done = true; return(true); }
internal override void Load() { try { WordDocument = WordOpen(directory); List <Guid> reasonCustomerID = new List <Guid>(); decimal totalSum = 0; decimal amountWorks = 0; decimal sumWorks = 0; decimal amountMaterials = 0; decimal sumMaterials = 0; string powerOfattorneyInfo = null; using (var context = new DbSSContext()) { var applicationInfo = context.Application.Where(a => a.Number == NumberApplication).Select(a => new { a.Number, ID_contractor = a.Car.Contractor.ID, ID_contactPerson = a.PowerOfAttorney.ID_contactPerson == null ? null : (Guid?)a.PowerOfAttorney.ID_contactPerson, Contractor = a.Car.Contractor.ShortName, a.Car.Contractor.Address, Phone = a.Car.Contractor.Phone, Model = a.Car.Model.Name, a.Car.VIN, a.Car.LicensePlate, a.Car.NumberBody, a.Car.Price, a.Car.Mileage, Color = a.Car.Color, a.Car.Year, ContactPerson = string.IsNullOrEmpty(a.PowerOfAttorney.ContactPerson.FFP) ? null : a.PowerOfAttorney.ContactPerson.FFP, PhoneContactPerson = string.IsNullOrEmpty(a.PowerOfAttorney.ContactPerson.Phone) ? null : a.PowerOfAttorney.ContactPerson.Phone, AddressContactPerson = string.IsNullOrEmpty(a.PowerOfAttorney.ContactPerson.Address) ? null : a.PowerOfAttorney.ContactPerson.Address, PowerOfAttorneyNumber = string.IsNullOrEmpty(a.PowerOfAttorney.Number) ? null : a.PowerOfAttorney.Number, PowerOfAttorneyDate = a.PowerOfAttorney.Date == null ? null : (DateTime?)a.PowerOfAttorney.Date, Employee = a.Employee.FFP, a.Readiness, a.Extradition }).First(); reasonCustomerID = context.ReasonCustomer.Where(rc => rc.Number == applicationInfo.Number).Select(rc => rc.ID).ToList(); var workInfo = context.Work.Where(w => reasonCustomerID.Contains(w.ID_reasonCustomer)).OrderBy(w => new { w.Nomenclature.ShortName }).Select(w => new { Work = w.Nomenclature.ShortName, w.Amount, w.NormOfTime, PriceWorkingHour = w.WorkingHour.Price, Sum = w.WorkingHour.Price * w.Amount * w.NormOfTime }).ToList(); Word.Table workTable = WordDocument.Tables[1]; workTable.AutoFitBehavior(Word.WdAutoFitBehavior.wdAutoFitFixed); for (int i = 1; i <= workInfo.Count; i++) { workTable.Rows.Add(); if (i == 1) { SetParameterNomenclatureRow(workTable); } var work = workInfo[i - 1]; var currentRow = workTable.Rows[i + 1]; currentRow.Cells[1].Range.Text = work.Work; currentRow.Cells[2].Range.Text = work.Amount.ToString(); currentRow.Cells[3].Range.Text = work.NormOfTime.ToString("0.00"); currentRow.Cells[4].Range.Text = work.PriceWorkingHour.ToString(); currentRow.Cells[5].Range.Text = work.Sum.ToString(); amountWorks += work.Amount; sumWorks += work.Sum; totalSum += sumWorks; } MergeTotalRow(workTable, "Итого:", amountWorks, totalSum); ReplaceWordStub("{SumWork}", DateAndMoneyConverter.CurrencyToTxt((double)sumWorks, false)); var materialInfo = context.Material.Where(m => m.Customer == false && reasonCustomerID.Contains(m.ID_reasonCustomer)).Select(m => new { m.Customer, Material = m.Nomenclature.ShortName, m.Amount, Unit = m.Nomenclature.Unit.Name, m.Price, Sum = m.Amount * m.Price }).OrderBy(m => new { m.Material }).ToList(); Word.Table materialTable = WordDocument.Tables[2]; materialTable.AutoFitBehavior(Word.WdAutoFitBehavior.wdAutoFitFixed); for (int i = 1; i <= materialInfo.Count; i++) { materialTable.Rows.Add(); if (i == 1) { SetParameterNomenclatureRow(materialTable); } var material = materialInfo[i - 1]; var currentRow = materialTable.Rows[i + 1]; currentRow.Cells[1].Range.Text = material.Material; currentRow.Cells[2].Range.Text = material.Amount.ToString(); currentRow.Cells[3].Range.Text = material.Unit; currentRow.Cells[4].Range.Text = material.Price.ToString(); currentRow.Cells[5].Range.Text = material.Sum.ToString(); sumMaterials += material.Sum; amountMaterials += material.Amount; totalSum += sumMaterials; } MergeTotalRow(materialTable, "Итого:", amountMaterials, sumMaterials); ReplaceWordStub("{SumMaterial}", DateAndMoneyConverter.CurrencyToTxt((double)sumMaterials, false)); // Итого по документу ReplaceWordStub("{SumDocument}", totalSum.ToString("0.00 рублей")); ReplaceWordStub("{SumDocumentText}", DateAndMoneyConverter.CurrencyToTxt((double)totalSum, false)); if (!string.IsNullOrEmpty(applicationInfo.PowerOfAttorneyNumber)) { powerOfattorneyInfo = string.Format("№{0} от {1:dd MMMM yyyy}", applicationInfo.PowerOfAttorneyNumber, applicationInfo.PowerOfAttorneyDate); } ReplaceWordStub("{Number}", applicationInfo.Number.ToString()); ReplaceWordStub("{Date}", GetDateString(applicationInfo.Readiness)); ReplaceWordStub("{Contractor}", applicationInfo.Contractor); ReplaceWordStub("{Phone}", applicationInfo.Phone); ReplaceWordStub("{AddressContractor}", applicationInfo.Address); ReplaceWordStub("{ContactPerson}", applicationInfo.ContactPerson); ReplaceWordStub("{PhoneContactPerson}", applicationInfo.PhoneContactPerson); ReplaceWordStub("{PowerOfAttorney}", powerOfattorneyInfo); ReplaceWordStub("{AddressContactPerson}", applicationInfo.AddressContactPerson); ReplaceWordStub("{Model}", applicationInfo.Model); ReplaceWordStub("{LicensePlate}", applicationInfo.LicensePlate); ReplaceWordStub("{Year}", applicationInfo.Year.ToString("yyyy")); ReplaceWordStub("{PriceCar}", applicationInfo.Price == 0 ? null : applicationInfo.Price.ToString()); ReplaceWordStub("{VIN}", applicationInfo.VIN); ReplaceWordStub("{Mileage}", applicationInfo.Mileage.ToString()); ReplaceWordStub("{NumberBody}", applicationInfo.NumberBody); ReplaceWordStub("{Color}", applicationInfo.Color); //ReplaceWordStub("{AgreementConditions}", Properties.Settings.Default.AgreementConditions); //ReplaceWordStub("{TermsPurchaseMaterials}", Properties.Settings.Default.TermsPurchaseMaterials); //ReplaceWordStub("{Revealed}", applicationInfo.Revealed); //ReplaceWordStub("{Other}", applicationInfo.Other); //ReplaceWordStub("{Readiness}", applicationInfo.Readiness == null ? null : ((DateTime)applicationInfo.Readiness).ToString("dd MMMM yyyy")); //ReplaceWordStub("{Extradition}", applicationInfo.Extradition == null ? null : ((DateTime)applicationInfo.Extradition).ToString("dd MMMM yyyy")); ReplaceWordStub("{Guarantee}", Properties.Settings.Default.Guarantee); ReplaceWordStub("{Employee}", applicationInfo.Employee); } Save(); } catch (Exception ex) { ShowError(ex.Message); } }
public async static System.Threading.Tasks.Task CreateProductReport() { Word._Application oWord; Word._Document oDoc; try { API api = API.GetInstance(); List <Product> products = await api.AsyncGetCatalog <Product>(); if (products.Count == 0) { throw new Exception("В БД нет записей о товарах"); } var categories = products.GroupBy(p => p.Category?.Name); int rows = 0; foreach (var c in categories) { rows += 1 + c.Count(); } object oMissing = System.Reflection.Missing.Value; object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */ //Start Word and create a new document. oWord = new Word.Application(); oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); object start = 0, end = 0; Word.Range rng = oDoc.Range(ref start, ref end); rng.SetRange(rng.End, rng.End); // Header Paragraph header = oDoc.Content.Paragraphs.Add(ref oMissing); var rngReportHeader = header.Range; rngReportHeader.Text = "Отчет по остаткам"; rngReportHeader.Font.Size = 15; rngReportHeader.Font.Name = "Verdana"; rngReportHeader.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; rngReportHeader.InsertParagraphAfter(); // Add the table. Paragraph table = oDoc.Content.Paragraphs.Add(ref oMissing); var rngTable = table.Range; rngTable.Tables.Add(rngTable, rows + 1, 6, ref oMissing, ref oMissing); // Format the table and apply a style. Word.Table tbl = oDoc.Tables[1]; tbl.Range.Font.Size = 12; tbl.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; tbl.Range.ParagraphFormat.SpaceAfter = 0.0f; tbl.Borders.Enable = 1; tbl.Cell(1, 1).Range.Text = "ИД"; tbl.Cell(1, 2).Range.Text = "Название"; tbl.Cell(1, 3).Range.Text = "Ед."; tbl.Cell(1, 4).Range.Text = "Цена"; tbl.Cell(1, 5).Range.Text = "Количество"; tbl.Cell(1, 6).Range.Text = "Сумма"; for (int j = 1; j <= 6; j++) { var cell = tbl.Cell(1, j); cell.Range.Font.Bold = 1; cell.Range.Font.Name = "Verdana"; cell.Range.Font.Size = 12; cell.Shading.BackgroundPatternColor = WdColor.wdColorGray25; //Center alignment for the Header cells cell.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; cell.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; } int i = 2; foreach (var c in categories) { tbl.Cell(i, 1).Range.Text = c.Key; tbl.Rows[i].Cells.Merge(); i++; foreach (var p in c) { tbl.Cell(i, 1).Range.Text = p.Id.ToString(); tbl.Cell(i, 2).Range.Text = p.Name; tbl.Cell(i, 3).Range.Text = p.Unit?.ToString(); tbl.Cell(i, 4).Range.Text = p.Price.ToString() + " руб."; tbl.Cell(i, 5).Range.Text = p.Quantity.ToString(); tbl.Cell(i, 6).Range.Text = (p.Price * (decimal)p.Quantity).ToString() + " руб."; i++; } } tbl.AutoFitBehavior(WdAutoFitBehavior.wdAutoFitContent); tbl.TopPadding = 6f; tbl.RightPadding = 6f; tbl.LeftPadding = 6f; tbl.BottomPadding = 6f; tbl.Range.InsertParagraphAfter(); // Footer Paragraph footer = oDoc.Content.Paragraphs.Add(ref oMissing); var rngReportFooter = footer.Range; rngReportFooter.Text = "\nНа дату: " + DateTime.Now.ToString(); rngReportFooter.Font.Size = 10; rngReportFooter.Font.Name = "Verdana"; rngReportFooter.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight; rngReportFooter.InsertParagraphAfter(); oWord.Visible = true; return; } catch { throw; } finally { oDoc = null; oWord = null; } }
public async static System.Threading.Tasks.Task CreateOrderReport(DateTime first, DateTime second) { Word._Application oWord; Word._Document oDoc; try { API api = API.GetInstance(); var list = await api.AsyncGetCatalog <Order>(); var completedOrders = list.Where(o => o.IsComplete & o.Date >= first & o.Date <= second).ToList(); if (completedOrders.Count == 0) { throw new Exception("В БД нет записей о завершенных заказах за данный период"); } int rows = 0; foreach (var order in completedOrders) { rows += 2 + order.OrderProducts.Count; } object oMissing = System.Reflection.Missing.Value; object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */ // Start Word and create a new document. oWord = new Word.Application(); oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); object start = 0, end = 0; Word.Range rng = oDoc.Range(ref start, ref end); rng.SetRange(rng.End, rng.End); // Header Paragraph header = oDoc.Content.Paragraphs.Add(ref oMissing); var rngReportHeader = header.Range; rngReportHeader.Text = $"Отчет по завершенным заказам\nза период {first.ToShortDateString()} – {second.ToShortDateString()}"; rngReportHeader.Font.Size = 14; rngReportHeader.Font.Name = "Verdana"; rngReportHeader.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; rngReportHeader.InsertParagraphAfter(); // Add the table. Paragraph table = oDoc.Content.Paragraphs.Add(ref oMissing); var rngTable = table.Range; rngTable.Tables.Add(rngTable, rows + 1, 4, ref oMissing, ref oMissing); // Format the table and apply a style. Word.Table tbl = oDoc.Tables[1]; tbl.Range.Font.Size = 12; tbl.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; tbl.Range.ParagraphFormat.SpaceAfter = 0.0f; tbl.Borders.Enable = 1; tbl.Cell(1, 1).Range.Text = "ИД"; tbl.Cell(1, 2).Range.Text = "Заказчик"; tbl.Cell(1, 3).Range.Text = "Дата"; tbl.Cell(1, 4).Range.Text = "Сумма"; for (int j = 1; j <= 4; j++) { var cell = tbl.Cell(1, j); cell.Range.Font.Bold = 1; cell.Range.Font.Name = "Verdana"; cell.Range.Font.Size = 12; cell.Shading.BackgroundPatternColor = WdColor.wdColorGray25; //Center alignment for the Header cells cell.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; cell.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; } int i = 2; foreach (var o in completedOrders) { tbl.Cell(i, 1).Range.Text = o.Id.ToString(); tbl.Cell(i, 2).Range.Text = o.Customer.Name; tbl.Cell(i, 3).Range.Text = o.Date.ToShortDateString(); tbl.Cell(i, 4).Range.Text = o.OrderProducts.Sum(op => op.Product.Price * (decimal)op.Quantity).ToString() + " руб."; tbl.Rows[i].Borders[WdBorderType.wdBorderTop].LineWidth = WdLineWidth.wdLineWidth300pt; i++; tbl.Cell(i, 2).Range.Text = "Товар"; tbl.Cell(i, 3).Range.Text = "Кол-во"; tbl.Cell(i, 4).Range.Text = "Сумма"; tbl.Rows[i].Range.Font.Bold = 1; i++; foreach (var op in o.OrderProducts) { tbl.Cell(i, 1).Borders[WdBorderType.wdBorderTop].Visible = false; tbl.Cell(i, 2).Range.Text = op.Product.Name; tbl.Cell(i, 3).Range.Text = op.Quantity.ToString(); tbl.Cell(i, 4).Range.Text = (op.Product.Price * (decimal)op.Quantity).ToString() + " руб."; i++; } } tbl.Columns.First.AutoFit(); tbl.AutoFitBehavior(WdAutoFitBehavior.wdAutoFitWindow); tbl.TopPadding = 6f; tbl.RightPadding = 6f; tbl.LeftPadding = 6f; tbl.BottomPadding = 6f; // Footer Paragraph footer = oDoc.Content.Paragraphs.Add(ref oMissing); var rngReportFooter = footer.Range; rngReportFooter.Text = "\nОтчет создан: " + DateTime.Now.ToString(); rngReportFooter.Font.Size = 10; rngReportFooter.Font.Name = "Verdana"; rngReportFooter.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight; rngReportFooter.InsertParagraphAfter(); oWord.Visible = true; return; } catch { throw; } finally { oDoc = null; oWord = null; } }
private void AddEntry(RecordSearch record) { //Date Word.Paragraph dateHeader = document.Content.Paragraphs.Add(ref missing); dateHeader.Range.Paragraphs.SpaceAfter = 0; try { dateHeader.Range.Text = record.DateOfResponse.ToDateString() + "\n"; } catch { dateHeader.Range.Text = "Missing date of response."; dateHeader.Range.Font.Bold = 1; dateHeader.Range.Font.Color = Word.WdColor.wdColorDarkRed; _errorCount++; } dateHeader.Range.InsertParagraphAfter(); //Address, PEID, & Invoice # Word.Table iTable = document.Tables.Add(dateHeader.Range, 1, 3, ref missing, ref missing); iTable.AllowAutoFit = true; iTable.AutoFitBehavior(Word.WdAutoFitBehavior.wdAutoFitWindow); iTable.Columns[1].PreferredWidthType = Word.WdPreferredWidthType.wdPreferredWidthPercent; iTable.Columns[1].PreferredWidth = 40; iTable.Columns[2].PreferredWidthType = Word.WdPreferredWidthType.wdPreferredWidthPercent; iTable.Columns[2].PreferredWidth = 30; //--Address if (record.BillingAddress.ValidateMinimalCompleteness()) { if (string.IsNullOrWhiteSpace(record.BillingAddress.AddressLine2)) { iTable.Rows[1].Cells[1].Range.Text = string.Format("{0}\r\n{1}\r\n{2}, {3} {4}", record.BillingAddress.AddressName, record.BillingAddress.AddressLine1, record.BillingAddress.City, record.BillingAddress.State, record.BillingAddress.ZIP); } else { iTable.Rows[1].Cells[1].Range.Text = string.Format("{0}\r\n{1}\r\n{2}\r\n{3}, {4} {5}", record.BillingAddress.AddressName, record.BillingAddress.AddressLine1, record.BillingAddress.AddressLine2, record.BillingAddress.City, record.BillingAddress.State, record.BillingAddress.ZIP); } } else { iTable.Rows[1].Cells[1].Range.Text = "Missing billing address information."; iTable.Rows[1].Cells[1].Range.Font.Bold = 1; iTable.Rows[1].Cells[1].Range.Font.Color = Word.WdColor.wdColorDarkRed; _errorCount++; } //--PEID if (!string.IsNullOrWhiteSpace(record.ClientModel.NewPEID)) { iTable.Rows[1].Cells[2].Range.Text = string.Format("PEID # " + record.ClientModel.NewPEID); } else if (!string.IsNullOrWhiteSpace(record.ClientModel.OldPEID)) { iTable.Rows[1].Cells[2].Range.Text = string.Format("PEID # " + record.ClientModel.OldPEID); } else { iTable.Rows[1].Cells[2].Range.Text = "Missing PEID."; iTable.Rows[1].Cells[2].Range.Font.Bold = 1; iTable.Rows[1].Cells[2].Range.Font.Color = Word.WdColor.wdColorDarkRed; _errorCount++; } iTable.Rows[1].Cells[2].Range.Bold = 1; iTable.Rows[1].Cells[2].Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight; //--Invoice # iTable.Rows[1].Cells[3].Range.Text = "Invoice #"; iTable.Rows[1].Cells[3].Range.Bold = 1; iTable.Range.InsertParagraphAfter(); //Person, Project Name, Requestor, IC File # Word.Paragraph projectInfo = document.Content.Paragraphs.Add(ref missing); string attentionTo; if (string.IsNullOrWhiteSpace(record.BillingAddress.AttentionTo)) { attentionTo = ""; } else { attentionTo = "\r\nATTN: " + record.BillingAddress.AttentionTo; } string fileNumber = "IC File # " + record.GetFileNumberFormatted(); if (string.IsNullOrWhiteSpace(record.Requestor.FirstName)) { projectInfo.Range.Text = string.Format("{0}\r\n>>\r\nRE: {1}; {2}\r\n>>", attentionTo, record.ProjectName, fileNumber); } else { projectInfo.Range.Text = string.Format("{0}\r\n>>\r\nRE: {1} (Requested By: {2} {3}); {4}\r\n>>", attentionTo, record.ProjectName, record.Requestor.FirstName, record.Requestor.LastName, fileNumber); } object startRange = projectInfo.Range.End - (fileNumber.Length + 4); object endRange = projectInfo.Range.End - 3; Word.Range toBold = document.Range(ref startRange, ref endRange); toBold.Bold = 1; projectInfo.Range.InsertParagraphAfter(); //Billing Info Word.Table bTable = document.Content.Tables.Add(projectInfo.Range, 1, 2, ref missing); bTable.AllowAutoFit = true; bTable.AutoFitBehavior(Word.WdAutoFitBehavior.wdAutoFitWindow); bTable.Columns[1].PreferredWidthType = Word.WdPreferredWidthType.wdPreferredWidthPercent; bTable.Columns[1].PreferredWidth = 25; //--Total try { bTable.Rows[1].Cells[1].Range.Text = "Amount Due: $" + record.Fee.TotalProjectCost; } catch { bTable.Rows[1].Cells[1].Range.Text = "Missing PEID."; bTable.Rows[1].Cells[1].Range.Font.Bold = 1; bTable.Rows[1].Cells[1].Range.Font.Color = Word.WdColor.wdColorDarkRed; _errorCount++; } //--Fees & Surcharge string chargeInformation = ""; decimal runningTotal = 0; foreach (ICharge charge in record.Fee.Charges) { if (charge.TotalCost <= 0) { continue; } switch (charge.Type) { case "variable": VariableCharge vCharge = (VariableCharge)charge; chargeInformation += string.Format(" {0} - {1} {2} @ ${3} per {4}\n", vCharge.Name, vCharge.Count, vCharge.UnitNamePlural, vCharge.Cost, vCharge.UnitName); runningTotal += vCharge.TotalCost; break; case "boolean": BooleanCharge bCharge = (BooleanCharge)charge; chargeInformation += string.Format(" {0} - ${1}\n", bCharge.Name, bCharge.TotalCost); runningTotal += bCharge.TotalCost; break; case "categorical": CategoricalCharge cCharge = (CategoricalCharge)charge; chargeInformation += string.Format(" {0} - {1} {2} - ${3}\n", cCharge.Name, cCharge.Count, cCharge.UnitNamePlural, cCharge.TotalCost); runningTotal += cCharge.TotalCost; break; default: break; } } string surcharge = ""; if (record.Fee.IsPriority) { surcharge += " Priority Surcharge Fee: $" + (record.Fee.TotalProjectCost - runningTotal) + "\n"; } if (record.Fee.IsEmergency) { surcharge += " Emergency Surcharge Fee: $" + record.Fee.TotalProjectCost + "\n"; } bTable.Rows[1].Cells[2].Range.Text = "Information\n" + chargeInformation + surcharge + "Please include the invoice number on your remittance"; bTable.Range.InsertParagraphAfter(); //Finish with line InsertLine(); }
public static void StartWordOtchot(Group g, Predmet p, Lesson l, BindingList <Student> tmpclass) { int count = tmpclass.Count; try { File.WriteAllBytes("Полесский государственный университет.docx", Resources.Полесский_государственный_университет); } catch (Exception) { MessageBox.Show("Закройте прошлый документ!!!"); } Word.Application app = new Word.Application(); Word.Document doc = app.Documents.Open(Environment.CurrentDirectory + @"\Полесский государственный университет.docx", ReadOnly: false, Visible: true); try { Word.Range r = doc.Bookmarks["fac"].Range; r.Text = g.Fac; r.Font.Bold = 0; r.Select(); r = doc.Bookmarks["spec"].Range; r.Text = g.Spec; r.Font.Bold = 0; r.Select(); r = doc.Bookmarks["kurs"].Range; r.Text = g.Curs.ToString(); r.Font.Bold = 0; r.Select(); r = doc.Bookmarks["group"].Range; r.Text = g.ToString(); r.Font.Bold = 0; r.Select(); r = doc.Bookmarks["lesson"].Range; r.Text = p.Name; r.Font.Bold = 0; r.Select(); r = doc.Bookmarks["prepod"].Range; r.Text = Server.myInfo.FIO; r.Font.Bold = 0; r.Select(); r = doc.Bookmarks["data"].Range; r.Text = DateTime.Today.ToLongDateString(); r.Font.Bold = 0; r.Select(); //формирование таблицы r = doc.Bookmarks["tabel"].Range; Object Def = Word.WdDefaultTableBehavior.wdWord8TableBehavior; if (l.Zanatie.Count != 0) { Object Def1 = Word.WdAutoFitBehavior.wdAutoFitWindow; doc.Tables.Add(r, 2 + count, 4 + l.Zanatie.Count, Def, Def1); Word.Table tabl = doc.Tables[1]; tabl.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle; tabl.Borders.InsideLineStyle = Word.WdLineStyle.wdLineStyleSingle; tabl.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; //ширина колонок tabl.Cell(1, 1).Column.SetWidth(23f, Word.WdRulerStyle.wdAdjustNone); tabl.Cell(1, 2).Column.SetWidth(170f, Word.WdRulerStyle.wdAdjustNone); tabl.Cell(1, tabl.Columns.Count - 1).Column.SetWidth(50f, Word.WdRulerStyle.wdAdjustNone); tabl.Cell(1, tabl.Columns.Count).Column.SetWidth(80f, Word.WdRulerStyle.wdAdjustNone); tabl.Rows[2].SetHeight(120f, Word.WdRowHeightRule.wdRowHeightAuto); //шапка { tabl.Cell(1, 1).Merge(tabl.Cell(2, 1)); tabl.Cell(1, 2).Merge(tabl.Cell(2, 2)); tabl.Cell(1, tabl.Columns.Count - 1).Merge(tabl.Cell(2, tabl.Columns.Count - 1)); tabl.Cell(1, tabl.Columns.Count).Merge(tabl.Cell(2, tabl.Columns.Count)); tabl.Cell(1, 3).Merge(tabl.Cell(1, tabl.Columns.Count - 2)); tabl.Cell(1, 1).Range.Text = "№ п/ п"; tabl.Cell(1, 1).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; tabl.Cell(1, 2).Range.Text = "Фамилия, Имя, Отчество студента"; tabl.Cell(1, 2).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; tabl.Cell(1, 3).Range.Text = "Оценка по формам текущего контроля"; tabl.Cell(1, 4).Range.Text = "Оценка текущей успеваемости"; tabl.Cell(1, 4).Range.Orientation = Word.WdTextOrientation.wdTextOrientationUpward; tabl.Cell(1, 4).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; tabl.Cell(1, 5).Range.Text = "Подпись преподавателя"; tabl.Cell(1, 5).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; tabl.Cell(1, 5).Range.Orientation = Word.WdTextOrientation.wdTextOrientationUpward; } for (int i = 1; i <= count; i++) { tabl.Cell(2 + i, 1).Range.Text = i.ToString(); } for (int i = 1; i <= count; i++) { tabl.Cell(2 + i, 2).Range.Text = tmpclass[i - 1].FIO; } for (int i = 0; i < l.Zanatie.Count; i++) { tabl.Cell(2, 3 + i).Range.Text = l.Zanatie[i].Name; tabl.Cell(2, 3 + i).VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; tabl.Cell(2, 3 + i).Range.Orientation = Word.WdTextOrientation.wdTextOrientationUpward; } foreach (Zanatie item in l.Zanatie) { foreach (var itemDost in item.Dost) { tabl.Cell(3 + tmpclass.IndexOf(tmpclass.Where(x => x.Id == itemDost.Student_id).ToList()[0]), 3 + l.Zanatie.IndexOf(item)).Range.Text = itemDost.Ocenka.ToString(); } } for (int i = 0; i < count; i++) { int kol = 0; double srball = 0; for (int k = 0; k < l.Zanatie.Count; k++) { int temp; if (tabl.Cell(3 + i, 3 + k).Range.Text.Length != 0) { string m = tabl.Cell(3 + i, 3 + k).Range.Text.Remove(tabl.Cell(3 + i, 3 + k).Range.Text.IndexOf('\r')); if (Int32.TryParse(m, out temp)) { kol++; srball += temp; } } } if (kol > 0) { tabl.Cell(3 + i, 3 + l.Zanatie.Count).Range.Text = (srball / kol).ToString("F1"); } } tabl.AutoFitBehavior(Word.WdAutoFitBehavior.wdAutoFitWindow); } else { MessageBox.Show("Заполните таблицу "); } //показать программу app.Visible = true; } catch (Exception) { doc.Close(); } try { } catch (Exception e) { Console.WriteLine(e.Message); } }
//Опис: Методот овозможува прибирање на сите податоци според избраните филтри од UI, задавање на изглед на самиот документ //Влезни параметри: успешно, неуспешно, дата од (за Логови), дата до (за Логови),корисник, провајдер, сервис public MemoryStream CreatingWordDocument(bool successfully, bool unsuccessfully, DateTime?fromDate, DateTime?toDate, string consumer = "", string provider = "", string service = "") { var messageLogs = PrepareDataForReports(successfully, unsuccessfully, fromDate, toDate, consumer, provider, service); _logger.Info("CreatingWordDocument get message logs from PrepareDataForReports, count: " + messageLogs.Count); try { var winword = new Microsoft.Office.Interop.Word.Application(); object missing = System.Reflection.Missing.Value; Document document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing); document.PageSetup.TopMargin = InchesToPoints(0.9f); document.PageSetup.BottomMargin = InchesToPoints(0.9f); document.PageSetup.LeftMargin = InchesToPoints(0.9f); document.PageSetup.RightMargin = InchesToPoints(0.9f); var macCultureInfo = CultureInfo.CreateSpecificCulture("mk-MK"); foreach (Section section in document.Sections) { //Get the header range and add the header details. Range headerRange = section.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range; headerRange.Fields.Add(headerRange, WdFieldType.wdFieldPage); headerRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight; headerRange.Font.Name = "Calibri"; headerRange.Font.ColorIndex = WdColorIndex.wdBlue; headerRange.Font.Size = 10; headerRange.Text = "Статистика за период " + fromDate.Value.ToString("dd.MM.yyyy", macCultureInfo) + " - " + toDate.Value.ToString("dd.MM.yyyy", macCultureInfo); } foreach (Section wordSection in document.Sections) { //Get the footer range and add the footer details. Range footerRange = wordSection.Footers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range; footerRange.Font.ColorIndex = WdColorIndex.wdDarkRed; footerRange.Font.Size = 10; footerRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; footerRange.Text = "Детали за повикување на сервиси"; } #region All services bool allServices = false; if (string.IsNullOrEmpty(service)) { allServices = true; Paragraph para1 = document.Content.Paragraphs.Add(ref missing); para1.Range.Text = "Сервиси и вкупен број на повикувања:"; para1.Range.InsertParagraphAfter(); } if (allServices) { foreach (var messageLog in messageLogs) { foreach (var calledService in messageLog.ListServices) { Paragraph para1 = document.Content.Paragraphs.Add(ref missing); para1.Range.Text = "Сервис: " + calledService.ServiceName + ": " + calledService.TotalCalledTimes; para1.Range.InsertParagraphAfter(); } } } #endregion foreach (var messageLog in messageLogs) { foreach (var services in messageLog.ListServices) { Paragraph para1 = document.Content.Paragraphs.Add(ref missing); object styleHeading1 = "Heading 1"; para1.Range.set_Style(ref styleHeading1); para1.Range.Text = "Сервис: " + services.ServiceName; // para1.SpaceBefore = InchesToPoints(0.6f); para1.Range.InsertParagraphAfter(); //Add paragraph with Heading 2 style Paragraph para2 = document.Content.Paragraphs.Add(ref missing); //object styleHeading2 = "Heading 3"; para2.Range.set_Style(WdBuiltinStyle.wdStyleIntenseReference); para2.Range.Text = "Вкупен број на повикувања:" + services.TotalCalledTimes; para2.Range.InsertParagraphAfter(); Paragraph para3 = document.Content.Paragraphs.Add(ref missing); para3.Range.Text = Environment.NewLine + "Детали за повикување на сервисот од институции"; para3.Range.InsertParagraphAfter(); //Na baranje na MIOA, dokolku od UI se filtrira po uspeshni ili neuspeshni, vo dokument fajlot treba da gi dava samo tie koloni int count = 0; if (successfully || unsuccessfully) { count = 2; } if (!successfully && !unsuccessfully) { count = 4; } Table consumersTable = document.Tables.Add(para3.Range, services.ListConsumers.Count + 1, count, ref missing, ref missing); consumersTable.Borders.Enable = 1; consumersTable.AutoFitBehavior(WdAutoFitBehavior.wdAutoFitWindow); //Adding header row for (int i = 1; i <= count; i++) { consumersTable.Cell(1, i).Range.Font.Bold = 1; consumersTable.Cell(1, i).Range.Font.Name = "Calibri"; consumersTable.Cell(1, i).Range.Font.Size = 10; consumersTable.Cell(1, i).Range.Font.Color = WdColor.wdColorGray75; consumersTable.Cell(1, i).Shading.BackgroundPatternColor = WdColor.wdColorGray20; consumersTable.Cell(1, i).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; consumersTable.Cell(1, i).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; if (i == 1) { consumersTable.Cell(1, i).Range.Paragraphs.SpaceBefore = 7; consumersTable.Cell(1, i).Range.Text = "Институција"; } if (successfully) { if (i == 2) { consumersTable.Cell(1, i).Range.Paragraphs.SpaceBefore = 7; consumersTable.Cell(1, i).Range.Text = "Успешни трансакции"; } } else if (unsuccessfully) { //ako nema uspeshni, togash kolonata za neuspeshni ima edna pozicija minus, sega e na pozicija 2 if (i == 2) { consumersTable.Cell(1, i).Range.Paragraphs.SpaceBefore = 7; consumersTable.Cell(1, i).Range.Text = "Неуспешни трансакции"; } } else { if (i == 2) { consumersTable.Cell(1, i).Range.Paragraphs.SpaceBefore = 7; consumersTable.Cell(1, i).Range.Text = "Успешни трансакции"; } if (i == 3) { consumersTable.Cell(1, i).Range.Paragraphs.SpaceBefore = 7; consumersTable.Cell(1, i).Range.Text = "Неуспешни трансакции"; } if (i == 4) { consumersTable.Cell(1, i).Range.Paragraphs.SpaceBefore = 7; consumersTable.Cell(1, i).Range.Text = "Вкупно трансакции"; } } } //Adding the rest of the rows for (int j = 0; j < services.ListConsumers.Count; j++) { consumersTable.Cell(j + 2, 1).Range.Text = services.ListConsumers[j].ConsumerName; for (int k = 0; k < services.ListConsumers[j].ListProviders.Count; k++) { if (successfully) { consumersTable.Cell(j + 2, 2).Range.Text = services.ListConsumers[j].ListProviders[k].SuccesfullCalls.toString(); } else if (unsuccessfully) { //ako nema uspeshni, togash kolonata neuspeshni ima edna pozicija minus, t.e sega e na pozicija 2 consumersTable.Cell(j + 2, 2).Range.Text = services.ListConsumers[j].ListProviders[k].UnSuccesfullCalls.toString(); } else { consumersTable.Cell(j + 2, 2).Range.Text = services.ListConsumers[j].ListProviders[k].SuccesfullCalls.toString(); consumersTable.Cell(j + 2, 3).Range.Text = services.ListConsumers[j].ListProviders[k].UnSuccesfullCalls.toString(); consumersTable.Cell(j + 2, 4).Range.Text = services.ListConsumers[j].ListProviders[k].Count.toString(); } } } Paragraph para4 = document.Content.Paragraphs.Add(ref missing); para4.SpaceAfter = 7; para4.Range.InsertParagraphAfter(); } } object filename = AppSettings.Get <string>("StatisticWordDocumentPath"); document.SaveAs2(ref filename); document.Close(ref missing, ref missing, ref missing); winword.Quit(ref missing, ref missing, ref missing); var getDocument = File.ReadAllBytes(filename.toString()); var stream = new MemoryStream(getDocument); return(stream); } catch (Exception ex) { _logger.Error("Se sluci greska pri kreiranje na word dokumentot: ", ex); throw ex; } }
private void generateIndexPage(byte[] templateLocation, WordInterface wordInterface, Document wordDocument, int projectID) { lock (this.threadLock) { try { //Open the template from a temporary file. String tempTemplateFile = Path.GetTempFileName(); File.WriteAllBytes(tempTemplateFile, templateLocation); Document indexPageTemplate = wordInterface.app.Documents.Open(tempTemplateFile); //Copy template to main document. wordInterface.copyDocumentToOtherDocument(indexPageTemplate, wordDocument, false); wordDocument.Activate(); //Find index table template. Microsoft.Office.Interop.Word.Table tableTemplate = wordInterface.findTableWithTitle(wordDocument, "riskAssessmentIndex"); if (tableTemplate == null) { throw new Exception("Could not find riskAssessmentIndex table. Check your template."); } //Do not allow the column size to change. tableTemplate.AutoFitBehavior(WdAutoFitBehavior.wdAutoFitFixed); //Get all dagners from the database. DataView dangersView = new DataView(this.tbl_DangerTableAdapter.GetData()); //Loop throug the dangers. foreach (DataRowView dangerRow in dangersView) { //Get some dangersource data from the database. int oldPageCount = wordDocument.ComputeStatistics(WdStatistic.wdStatisticPages); string lastDangerSourceName = ""; DataView dangerSourceView = new DataView(this.get_RiskAssessment_Index_DataTableAdapter.GetData(projectID, (Int32)dangerRow["DangerID"])); //Copy table and set the header. Table indexTable = wordInterface.copyTable(wordDocument, tableTemplate.Range); indexTable.Rows[1].Range.Text = dangerRow["DangerGroupName"].ToString(); //Add danger sources to the danger group. foreach (DataRowView dangerSourceRow in dangerSourceView) { Row newTableRow; //Create new row when we get a different dangersource then the previous. if (lastDangerSourceName != dangerSourceRow["DangerSourceName"].ToString()) { lastDangerSourceName = dangerSourceRow["DangerSourceName"].ToString(); newTableRow = indexTable.Rows.Add(ref missing); } else { newTableRow = indexTable.Rows.Last; } newTableRow.Cells[1].Range.Text = lastDangerSourceName; //Does this dangersource has an risk associated with it? if (dangerSourceRow["RiskID"] != DBNull.Value) { newTableRow.Cells[2].Range.Text = "YES"; wordInterface.addTextToTableCell(newTableRow.Cells[3].Range, dangerSourceRow["RiskID"].ToString(), true); } else { newTableRow.Cells[2].Range.Text = "NO"; } //Does this dangersource has risks with remaining risk? if (dangerSourceRow["HasRemainingRisk"] != DBNull.Value) { wordInterface.addTextToTableCell(newTableRow.Cells[4].Range, dangerSourceRow["HasRemainingRisk"].ToString(), true); } } //Delete our row template. indexTable.Rows[3].Delete(); wordInterface.setAlternatingTableRowStyle(indexTable, ARA_Colors.ARA_Blue1, 4); //Set table on a new pages when it stretches over 2 pages. if (oldPageCount < wordDocument.ComputeStatistics(WdStatistic.wdStatisticPages)) { Range tableRange = indexTable.Range; tableRange.SetRange(wordDocument.Content.End - 2, wordDocument.Content.End + 2); //tableRange.SetRange(indexTable.Range.Start - 2, indexTable.Range.Start); wordInterface.insertPageBreakAtRange(indexTable.Range); } } //Delete a trailing enter after our template table. Range rng = tableTemplate.Range; rng.SetRange(rng.End, rng.End + 2); rng.Delete(); //Delete our template table and insert a pagebreak. tableTemplate.Delete(); wordInterface.insertPageBreakAtRange(wordDocument.Words.Last); // Close and release the Document object. if (indexPageTemplate != null) { ((_Document)indexPageTemplate).Close(ref paramFalse, ref missing, ref missing); File.Delete(tempTemplateFile); indexPageTemplate = null; } } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ARA_Constants.messageBoxSomethingWrongWhileGenerating + ex.Message, ARA_Constants.messageBoxSomethingWrongWhileGeneratingHeader, MessageBoxButtons.OK, MessageBoxIcon.Warning); } } }
internal override void Load() { try { WordDocument = WordOpen(directory); List <Guid> reasonCustomerID = new List <Guid>(); decimal sumRepair = 0; decimal amountMaterialsCustomer = 0; decimal sumMaterialsCustomer = 0; string powerOfattorneyInfo = null; using (var context = new DbSSContext()) { var applicationInfo = context.Application.Where(a => a.Number == NumberApplication).Select(a => new { a.Number, a.Date, ID_contractor = a.Car.Contractor.ID, ID_contactPerson = a.PowerOfAttorney.ID_contactPerson == null ? null : (Guid?)a.PowerOfAttorney.ID_contactPerson, Contractor = a.Car.Contractor.ShortName, a.Car.Contractor.Address, Phone = a.Car.Contractor.Phone, Model = a.Car.Model.Name, a.Car.VIN, a.Car.LicensePlate, a.Car.NumberBody, a.Car.Price, a.Car.Mileage, a.Car.Color, a.Car.Year, ContactPerson = string.IsNullOrEmpty(a.PowerOfAttorney.ContactPerson.FFP) ? null : a.PowerOfAttorney.ContactPerson.FFP, PhoneContactPerson = string.IsNullOrEmpty(a.PowerOfAttorney.ContactPerson.Phone) ? null : a.PowerOfAttorney.ContactPerson.Phone, AddressContactPerson = string.IsNullOrEmpty(a.PowerOfAttorney.ContactPerson.Address) ? null : a.PowerOfAttorney.ContactPerson.Address, PowerOfAttorneyNumber = string.IsNullOrEmpty(a.PowerOfAttorney.Number) ? null : a.PowerOfAttorney.Number, PowerOfAttorneyDate = a.PowerOfAttorney.Date == null ? null : (DateTime?)a.PowerOfAttorney.Date, Employee = a.Employee.FFP, a.FirstControlTime, a.SecondControlTime, a.Type, //a.Readiness, //a.Extradition, }).First(); var optionInfo = context.OptionCustomer.Where(oc => oc.Number == NumberApplication).OrderBy(oc => oc.Option.ShortName).Select(oc => oc.Option.ShortName).ToList(); Word.Table optionTable = WordDocument.Tables[2]; optionTable.AutoFitBehavior(Word.WdAutoFitBehavior.wdAutoFitFixed); for (int i = 1; i <= optionInfo.Count; i++) { optionTable.Rows.Add(); if (i == 1) { SetFontRow(optionTable.Rows[i + 1]); } optionTable.Rows[i + 1].Cells[1].Range.Text = optionInfo[i - 1].ToString(); } var repairInfo = context.ReasonCustomer.Where(rc => rc.Number == NumberApplication).Select(rc => new { rc.ID, rc.Reason.ShortName, rc.Reason.Type, Price = (rc.Material.Where(m => m.Customer == false).Sum(m => (m.Amount == null ? 0 : m.Amount) * (m.Price == null ? 0 : (decimal?)m.Price)) == null ? 0 : rc.Material.Where(m => m.Customer == false).Sum(m => (m.Amount == null ? 0 : m.Amount) * (m.Price == null ? 0 : (decimal?)m.Price))) + (rc.Work.Sum(w => (w.Amount == null ? 0 : (int?)w.Amount) * (w.NormOfTime == null ? 0 : w.NormOfTime) * (w.WorkingHour.Price == null ? 0 : w.WorkingHour.Price)) == null ? 0 : rc.Work.Sum(w => (w.Amount == null ? 0 : (int?)w.Amount) * (w.NormOfTime == null ? 0 : w.NormOfTime) * (w.WorkingHour.Price == null ? 0 : w.WorkingHour.Price))) }).OrderBy(rc => new { rc.ShortName }).ToList(); Word.Table reairTable = WordDocument.Tables[3]; reairTable.AutoFitBehavior(Word.WdAutoFitBehavior.wdAutoFitFixed); for (int i = 1; i <= repairInfo.Count; i++) { reairTable.Rows.Add(); var currentRow = reairTable.Rows[i + 1]; if (i == 1) { SetFontRow(currentRow); SetFontCell(currentRow.Cells[3], Word.WdParagraphAlignment.wdAlignParagraphRight, 0); } var repair = repairInfo[i - 1]; currentRow.Cells[1].Range.Text = repair.ShortName; currentRow.Cells[2].Range.Text = repair.Type; currentRow.Cells[3].Range.Text = repair.Price.ToString(); sumRepair += (decimal)repair.Price; reasonCustomerID.Add(repair.ID); } reairTable.Rows.Add(); int rowCount = reairTable.Rows.Count; object begCell = reairTable.Cell(rowCount, 1).Range.Start; object endCell = reairTable.Cell(rowCount, 2).Range.End; WordDocument.Range(ref begCell, ref endCell).Cells.Merge(); var repairTotalRow = reairTable.Rows[rowCount]; repairTotalRow.Cells[1].Range.Font.Bold = 1; repairTotalRow.Cells[1].Range.Text = "Итого:"; repairTotalRow.Cells[2].Range.Text = sumRepair.ToString("0.00"); var materialCustomerInfo = context.Material.Where(m => m.Customer == true && reasonCustomerID.Contains(m.ID_reasonCustomer)).Select(m => new { Material = m.Nomenclature.ShortName, m.Amount, Unit = m.Nomenclature.Unit.Name, m.Price, Sum = m.Amount * m.Price }).OrderBy(m => new { m.Material }).ToList(); Word.Table materialCustomerTable = WordDocument.Tables[4]; materialCustomerTable.AutoFitBehavior(Word.WdAutoFitBehavior.wdAutoFitFixed); for (int i = 1; i <= materialCustomerInfo.Count; i++) { materialCustomerTable.Rows.Add(); if (i == 1) { SetParameterNomenclatureRow(materialCustomerTable); } var materialCustomer = materialCustomerInfo[i - 1]; var currentRow = materialCustomerTable.Rows[i + 1]; currentRow.Cells[1].Range.Text = materialCustomer.Material; currentRow.Cells[2].Range.Text = materialCustomer.Amount.ToString(); currentRow.Cells[3].Range.Text = materialCustomer.Unit; currentRow.Cells[4].Range.Text = materialCustomer.Price.ToString(); currentRow.Cells[5].Range.Text = materialCustomer.Sum.ToString(); amountMaterialsCustomer += materialCustomer.Amount; sumMaterialsCustomer += materialCustomer.Sum; } MergeTotalRow(materialCustomerTable, "Всего:", amountMaterialsCustomer, sumMaterialsCustomer); if (!string.IsNullOrEmpty(applicationInfo.PowerOfAttorneyNumber)) { powerOfattorneyInfo = string.Format("№{0} от {1}", applicationInfo.PowerOfAttorneyNumber, GetDateString(applicationInfo.PowerOfAttorneyDate)); } ReplaceWordStub("{Number}", applicationInfo.Number.ToString()); ReplaceWordStub("{Date}", applicationInfo.Date.ToString("dd MMMM yyyy")); ReplaceWordStub("{TypeRepair}", applicationInfo.Type); ReplaceWordStub("{First}", GetDateString(applicationInfo.FirstControlTime)); ReplaceWordStub("{Second}", GetDateString(applicationInfo.SecondControlTime)); ReplaceWordStub("{Contractor}", applicationInfo.Contractor); ReplaceWordStub("{Phone}", applicationInfo.Phone); ReplaceWordStub("{AddressContractor}", applicationInfo.Address); ReplaceWordStub("{ContactPerson}", applicationInfo.ContactPerson); ReplaceWordStub("{PhoneContactPerson}", applicationInfo.PhoneContactPerson); ReplaceWordStub("{PowerOfAttorney}", powerOfattorneyInfo); ReplaceWordStub("{AddressContactPerson}", applicationInfo.AddressContactPerson); ReplaceWordStub("{Model}", applicationInfo.Model); ReplaceWordStub("{LicensePlate}", applicationInfo.LicensePlate); ReplaceWordStub("{Year}", applicationInfo.Year.ToString("yyyy")); ReplaceWordStub("{PriceCar}", applicationInfo.Price == 0 ? null : applicationInfo.Price.ToString()); ReplaceWordStub("{VIN}", applicationInfo.VIN); ReplaceWordStub("{Mileage}", applicationInfo.Mileage.ToString()); ReplaceWordStub("{NumberBody}", applicationInfo.NumberBody); ReplaceWordStub("{Color}", applicationInfo.Color); ReplaceWordStub("{AgreementConditions}", Properties.Settings.Default.AgreementConditions); ReplaceWordStub("{TermsPurchaseMaterials}", Properties.Settings.Default.TermsPurchaseMaterials); ReplaceWordStub("{Employee}", applicationInfo.Employee); ReplaceWordStub("{Sum}", DateAndMoneyConverter.CurrencyToTxt((double)sumRepair, false)); } Save(); } catch (Exception ex) { ShowError(ex.Message); } }