public void Create() { paragraphHeader = document.InsertParagraph(header + this.docNumber, false, formattingNormal); FormatToGost(paragraphHeader, Alignment.center); paragraphName = document.InsertParagraph(theme, false, formattingBold); FormatToGost(paragraphName, Alignment.center); paragraphTaskHeader = document.InsertParagraph(taskHeader + taskNumber, false, formattingNormal); FormatToGost(paragraphTaskHeader, Alignment.both); paragraphEmptyLine = document.InsertParagraph("\r", false, formattingNormal); FormatToGost(paragraphEmptyLine, Alignment.both); document.InsertParagraph(paragraphEmptyLine); paragraphCodeHeader = document.InsertParagraph(codeHeader, false, formattingNormal); FormatToGost(paragraphCodeHeader, Alignment.both); InsertCode(0); paragraphResultHeader = document.InsertParagraph(resultHeader, false, formattingNormal); InsertScreenshot(); FormatToGost(paragraphResultHeader, Alignment.both); document.InsertParagraph(paragraphEmptyLine); for (int i = 1; i < codeDirFolders.Length; i++) { InsertTask(i); } try { document.SaveAs(filePath); } catch (Exception) { MessageBox.Show("Ошибка в сохранении файла") } document.Dispose(); }
public void LoadSourceDocX(string filename) { sourceDocX?.Dispose( ); targetDocX?.Dispose( ); sourceDocX = DocX.Load(filename); targetDocX = sourceDocX.Copy( ); }
static void Main(string[] args) { //EPPlus (excel lib) DocX report = DocX.Create("Report.docx", DocumentTypes.Document); var paragraph = report.InsertParagraph("YoY Value Report", false, new Formatting() { Bold = true }); report.InsertParagraph(); report.InsertParagraph(); var table = report.InsertTable(2, 3); table.Rows[0].Cells[0].InsertParagraph("Year"); table.Rows[0].Cells[1].InsertParagraph("Value"); table.Rows[0].Cells[2].InsertParagraph("Remarks"); table.Design = TableDesign.ColorfulList; report.Save(); report.Dispose(); }
/// <summary> /// /// </summary> /// <param name="id"></param> /// <param name="docPath"></param> /// <returns></returns> public Task <string> WriteDocs(Guid id, string docPath) { DocX docX = DocX.Create(docPath, DocumentTypes.Document); var query = GetById(id); var docf = WriteDocf(query); docX.InsertDocument(docf); var docs = WriteDocs(query.JingFeis); docX.InsertDocument(docs); docX.SaveAs(docPath); docX.Dispose(); return(null); }
public void SaveFile(string outputLocation) { try { _templateDocx.SaveAs(outputLocation); } catch { throw new Exception("[ERROR] 無法寫入檔案:" + outputLocation + "\r\n"); } finally { _templateDocx.Dispose(); } }
private async void GenerateTickets(int count) { dialog = new SaveFileDialog(); dialog.Filter = "Документ word(*docx)|*.docx"; dialog.OverwritePrompt = true; if (dialog.ShowDialog() == true) { textBox.Text = dialog.FileName; } else { MessageBox.Show("Не удалось выбрать место и название файла для сохранения!"); return; } progressbar.Maximum = count; progressbar.Value = 0; answername = dialog.FileName; int size = answername.Count() - 5; answername = answername.Remove(size); size = answername.Count(); answername += "_answers.docx"; doc_output = DocX.Create(dialog.FileName); doc_answer = DocX.Create(answername); Grid_Start.Visibility = Visibility.Collapsed; Grid_Progress.Visibility = Visibility.Visible; for (int i = 1; i <= count; i++) { await Task.Factory.StartNew(() => Generate(i)); progressbar.Value = i; progressbar_text.Content = string.Format("{0}/{1}", i, count); } doc_output.Save(); doc_answer.Save(); send(); doc_output.Dispose(); doc_answer.Dispose(); Grid_Start.Visibility = Visibility.Visible; Grid_Progress.Visibility = Visibility.Collapsed; MessageBox.Show("Генерация задач успешно завершена...", "Сообщение: Статус", MessageBoxButton.OK); }
private Stream CreateLabel(int id) { var model = new ProfileBoxModel(); var profileBox = _profileBoxService.GetById(id); string label = profileBox.Name.ToUpper(); string profileCount = ""; if (!profileBox.ProfileType.Scanned) { profileCount = profileBox.ProfileCount.ToString(); } else { var profiles = _profileService.SearchProfilesByStatus(id, 0, 1, int.MaxValue, null, null); profileCount = profiles.Count(x => x.StatusId != (short)ProfileStatus.Deleted).ToString(); } string filePath = Server.MapPath(Url.Content("~/Template/Label.docx")); DocX document = DocX.Load(filePath); var outputStream = new MemoryStream(); document.ReplaceText("{Label}", label); document.ReplaceText("{count}", profileCount); // get placeholder image Novacode.Image img = document.Images[0]; // create barcode encoder var barcodeWriter = new BarcodeWriter { Format = BarcodeFormat.CODE_128, Options = new EncodingOptions { PureBarcode = false, Height = 100, Width = 300, Margin = 10 } }; // create barcode image var bitmap = barcodeWriter.Write(label); // replace place holder image in document with barcode image bitmap.Save(img.GetStream(FileMode.Create, FileAccess.Write), ImageFormat.Png); document.SaveAs(outputStream); outputStream.Position = 0; document.Dispose(); return(outputStream); }
public static string ParseWord(string path) { DocX doc = DocX.Load(path); string s = ""; foreach (var e in doc.Paragraphs) { if (e.Text.Length != 0) { s += e.Text + "\n"; } } if (doc != null) { doc.Dispose(); } return(s); }
protected virtual void Dispose(bool disposing) { if (disposing) { // get rid of managed resources if (excelPackage != null) { excelPackage.Dispose(); } if (documentTemplate != null) { documentTemplate.Dispose(); } } // get rid of unmanaged resources }
public ActionResult counter(analyzr.Models.CounterModel m, HttpPostedFileBase uploadFile) { if (m.inputText == null) { if (uploadFile != null && (uploadFile.ContentLength > 0)) { string filePath = System.IO.Path.Combine(HttpContext.Server.MapPath("../Uploads"), System.IO.Path.GetFileName(uploadFile.FileName)); uploadFile.SaveAs(filePath); DocX doc = null; try { doc = DocX.Load(uploadFile.InputStream); m.inputText = doc.Text.ToString(); ViewData["file_text"] = doc.Text.ToString(); m.doMaths(); ViewData["output_generated"] = true; doc.Dispose(); } catch (Exception ex) { ModelState.AddModelError("Uploaded file is not valid. Only docx format is supported.", ex); } finally { if (System.IO.File.Exists(filePath)) { System.IO.File.Delete(filePath); } } } else { ModelState.AddModelError("You must either upload a file or enter an input text", new Exception()); } } else { m.doMaths(); ViewData["output_generated"] = true; } return(View(m)); }
//一般 public string fullcheifsupervisor(WordTableInfo Info) { Common.Common.load_cheif_supervisor(); string fileName = Environment.CurrentDirectory + "\\" + "chief_supervisor.doc"; //WORD文档所在路径 string newfile = Common.Common.strAddfilesPath + Info.Teacher + Info.Time.Trim() + Info.Supervisor + ".doc"; //存储路径名称 DocX doc = DocX.Load(fileName); Table table = doc.Tables[0]; table.Rows[0].Cells[1].Paragraphs[0].ReplaceText("teacher", Info.Teacher); table.Rows[0].Cells[5].Paragraphs[0].ReplaceText("time", Info.Time.Substring(0, Info.Time.IndexOf(" "))); table.Rows[1].Cells[5].Paragraphs[0].ReplaceText("address", Info.Classroom + Info.Time.Substring(Info.Time.IndexOf(" ") + 1)); table.Rows[3].Cells[1].Paragraphs[0].ReplaceText("class", Info.Class); table.Rows[4].Cells[1].Paragraphs[0].ReplaceText("context", Info.Subject); if (!System.IO.File.Exists(Common.Common.strAddfilesPath)) { Directory.CreateDirectory(Common.Common.strAddfilesPath); } doc.SaveAs(newfile); doc.Dispose(); return(newfile); }
public string fullsupervisor(WordTableInfo Info) { Common.Common.load_supervisor(); string fileName1 = Environment.CurrentDirectory + "\\" + "supervisor.doc"; string newfile = Common.Common.strAddfilesPath + "\\" + Info.Teacher + Info.Time.Trim() + Info.Supervisor + ".doc"; DocX doc = DocX.Load(fileName1); doc.ReplaceText("title", "广东医学院教师课堂教学质量评价表" + "(" + Info.Teachingtype + ")"); Table table = doc.Tables[0]; table.Rows[0].Cells[1].Paragraphs[0].ReplaceText("Teacher", Info.Teacher); table.Rows[0].Cells[3].Paragraphs[0].ReplaceText("Perfession", Info.Perfession); table.Rows[0].Cells[5].Paragraphs[0].ReplaceText("Time", Info.Time.Substring(0, Info.Time.IndexOf(" "))); table.Rows[1].Cells[1].Paragraphs[0].ReplaceText("Class", Info.Class); table.Rows[1].Cells[3].Paragraphs[0].ReplaceText("address", Info.Classroom + Info.Time.Substring(Info.Time.IndexOf(" ") + 1)); table.Rows[2].Cells[1].Paragraphs[0].ReplaceText("Context", Info.Subject); if (!System.IO.File.Exists(Common.Common.strAddfilesPath)) { Directory.CreateDirectory(Common.Common.strAddfilesPath); } doc.SaveAs(newfile); doc.Dispose(); return(newfile); }
/// <summary> /// Закрывает открытое приложение Microsoft Word /// </summary> public override void CloseWordApp() { _document.Dispose(); }
private static void CreateClientReport(Client client) { DocX document = DocX.Create($"C:\\Users\\Acer\\Desktop\\Отчеты\\{client.Name}.docx"); document.MarginTop = 60; var p = document.InsertParagraph("ЮАБП"); p.FontSize(39).Bold().Color(Color.SkyBlue); p.Alignment = Alignment.center; p.IndentationAfter = 350; p.IndentationBefore = -20; var p1 = document.InsertParagraph("ООО «Юридическое Агентство"); p1.FontSize(8).Bold(); p1.Alignment = Alignment.center; p1.IndentationAfter = 350; p1.IndentationBefore = -20; var p2 = document.InsertParagraph("«БИЗНЕС - ПРОФИ»"); p2.FontSize(12).Bold(); p2.Alignment = Alignment.center; p2.IndentationAfter = 350; p2.IndentationBefore = -20; p2.LineSpacingAfter = 50; var p3 = document.InsertParagraph("Отчет о выполненной работе по клиенту "); p3.FontSize(16).Bold(); p3.Alignment = Alignment.center; var p4 = document.InsertParagraph($"«{client.Name}»"); p4.FontSize(16).Bold(); p4.Alignment = Alignment.center; p4.LineSpacingAfter = 30; var p5 = document.InsertParagraph($"Руб/Час – {client.OneHourePrice}"); p5.FontSize(12).Highlight(Highlight.yellow).Alignment = Alignment.right; p5.AppendLine($"Руб/Мин – {Math.Round(client.OneHourePrice / 60, 3)}").Highlight(Highlight.yellow).FontSize(12); var table = document.AddTable(1, 4); table.SetColumnWidth(0, 85); table.SetColumnWidth(1, 250); table.SetColumnWidth(2, 85); table.SetColumnWidth(3, 81); table.Design = TableDesign.MediumList1Accent5; table.Rows[0].Cells[0].Paragraphs[0].Append("Дата").FontSize(14).Bold().Alignment = Alignment.left; table.Rows[0].Cells[1].Paragraphs[0].Append("Выполненные работы").FontSize(14).Bold().Alignment = Alignment.left; table.Rows[0].Cells[2].Paragraphs[0].Append("Часы").FontSize(14).Bold().Alignment = Alignment.left; table.Rows[0].Cells[3].Paragraphs[0].Append("Цена").FontSize(14).Bold().Alignment = Alignment.left; var i = 1; foreach (var clientInfo in client.ClientInfoCollection) { table.InsertRow(); table.Rows[i].Cells[0].Paragraphs[0].Append(clientInfo.Date).FontSize(13).Alignment = Alignment.left; table.Rows[i].Cells[1].Paragraphs[0].Append(clientInfo.Question).FontSize(13).Alignment = Alignment.left; table.Rows[i].Cells[2].Paragraphs[0].Append($"{clientInfo.HourCount} ч. {clientInfo.MinuteCount} мин.").FontSize(13).Alignment = Alignment.left; table.Rows[i].Cells[3].Paragraphs[0].Append(Math.Round((clientInfo.StaticWorkPrice + (clientInfo.HourCount * 60 + clientInfo.MinuteCount) * client.OneHourePrice / 60), 3).ToString()).FontSize(13).Alignment = Alignment.left; i++; } document.InsertParagraph().InsertTableAfterSelf(table); var p6 = document.InsertParagraph($"ИТОГО: {client.TotalPrice} р"); p6.LineSpacingBefore = 50; p6.FontSize(16).Bold().Color(Color.Red); p6.Alignment = Alignment.left; document.Save(); document.Dispose(); ConvertToPdf(client); Message($"Отчет по клиенту {client.Name} сформирован"); }
public void GenerateDoc(string filePath) { if (string.IsNullOrWhiteSpace(filePath)) { return; } DocX doc = DocX.Load("Template/template.docx"); Paragraph cubicleAddress = doc.InsertParagraph(); cubicleAddress.Alignment = Alignment.left; cubicleAddress.AppendLine(); cubicleAddress.AppendLine(); cubicleAddress.AppendLine(); cubicleAddress.Append(_dataModel.AddressLine).Font(CalibriFont).FontSize(9); cubicleAddress.AppendLine(); var phoneString = $"Phone {_dataModel.Phone}"; cubicleAddress.Append(phoneString).Font(CalibriFont).FontSize(9); Table faxAndInvoiceInfo = doc.AddTable(2, 2); faxAndInvoiceInfo.SetWidthsPercentage(new float[] { 50, 50 }, null); var faxString = $"Fax {_dataModel.Fax}"; faxAndInvoiceInfo.Rows[0].Cells[0].Paragraphs.FirstOrDefault().Append(faxString) .Font(CalibriFont).FontSize(9).Alignment = Alignment.left; var invoiceString = $"INVOICE # { _dataModel.InvoiceId}"; faxAndInvoiceInfo.Rows[0].Cells[1].Paragraphs.FirstOrDefault().Append(invoiceString) .Font(CalibriFont).FontSize(8).Alignment = Alignment.right; var dateString = $"DATE: {_dataModel.InvoiceDate.ToShortDateString()}"; faxAndInvoiceInfo.Rows[1].Cells[1].Paragraphs.FirstOrDefault().Append(dateString) .Font(CalibriFont).FontSize(8).Alignment = Alignment.right; cubicleAddress.InsertTableAfterSelf(faxAndInvoiceInfo); Paragraph emptyParagraph = doc.InsertParagraph(); emptyParagraph.AppendLine(); emptyParagraph.AppendLine(); emptyParagraph.AppendLine(); Paragraph forParagraph = doc.InsertParagraph(); forParagraph.Alignment = Alignment.center; forParagraph.Append($"FOR: {_dataModel.PersonalName}").Font(CalibriFont).FontSize(11).Bold(); Table businessNameTable = doc.AddTable(6, 2); businessNameTable.SetWidthsPercentage(new float[] { 45.5f, 54.5f }, null); businessNameTable.Rows[0].Cells[0].Paragraphs.FirstOrDefault().Append("TO:") .Font(CalibriFont).FontSize(8).Bold().Alignment = Alignment.left; businessNameTable.Rows[0].Cells[1].Paragraphs.FirstOrDefault().Append(_dataModel.BusinessName) .Font(CalibriFont).FontSize(11).Bold().Alignment = Alignment.left; businessNameTable.Rows[1].Cells[0].Paragraphs.FirstOrDefault().Append(_davinciAddressModel.Name) .Font(CalibriFont).FontSize(9).Alignment = Alignment.left; businessNameTable.Rows[2].Cells[0].Paragraphs.FirstOrDefault().Append(_davinciAddressModel.AddressLine1) .Font(CalibriFont).FontSize(9).Alignment = Alignment.left; businessNameTable.Rows[3].Cells[0].Paragraphs.FirstOrDefault().Append(_davinciAddressModel.AddressLine2) .Font(CalibriFont).FontSize(9).Alignment = Alignment.left; var davinciPhone = $"Phone: {_davinciAddressModel.Phone}"; businessNameTable.Rows[4].Cells[0].Paragraphs.FirstOrDefault().Append(davinciPhone) .Font(CalibriFont).FontSize(9).Alignment = Alignment.left; var davinciFax = $"Fax: {_davinciAddressModel.Fax}"; businessNameTable.Rows[5].Cells[0].Paragraphs.FirstOrDefault().Append(davinciFax) .Font(CalibriFont).FontSize(9).Alignment = Alignment.left; forParagraph.InsertTableAfterSelf(businessNameTable); Paragraph emptyParagraph2 = doc.InsertParagraph(); emptyParagraph2.AppendLine(); Paragraph actionsParagraph = doc.InsertParagraph(); Table actionsTable = doc.AddTable(15, 4); actionsTable.SetWidthsPercentage(new float[] { 60, 20, 10, 10 }, null); // Borders for (int i = 0; i < actionsTable.RowCount; i++) { actionsTable.Rows[i].Height = 18; if (actionsTable.RowCount - 1 == i) { continue; } for (int j = 0; j < actionsTable.Rows[i].Cells.Count; j++) { actionsTable.Rows[i].Cells[j].SetBorder(TableCellBorderType.Bottom, new Border { Size = BorderSize.one }); actionsTable.Rows[i].Cells[j].SetBorder(TableCellBorderType.Left, new Border { Size = BorderSize.one }); actionsTable.Rows[i].Cells[j].SetBorder(TableCellBorderType.Right, new Border { Size = BorderSize.one }); actionsTable.Rows[i].Cells[j].VerticalAlignment = VerticalAlignment.Center; } } actionsTable.SetBorder(TableBorderType.Top, new Border { Size = BorderSize.one }); actionsTable.Rows[0].Cells[0].Paragraphs.FirstOrDefault().Append("DESCRIPTION") .Bold().Font(CalibriFont).FontSize(8).Alignment = Alignment.center; actionsTable.Rows[0].Cells[1].Paragraphs.FirstOrDefault().Append("DATE") .Bold().Font(CalibriFont).FontSize(8).Alignment = Alignment.center; actionsTable.Rows[0].Cells[2].Paragraphs.FirstOrDefault().Append("RATE") .Bold().Font(CalibriFont).FontSize(8).Alignment = Alignment.center; actionsTable.Rows[0].Cells[3].Paragraphs.FirstOrDefault().Append("AMOUNT") .Bold().Font(CalibriFont).FontSize(8).Alignment = Alignment.center; if (_dataModel.Actions != null && _dataModel.Actions.Count > 0) { int i = 1; foreach (var record in _dataModel.Actions) { actionsTable.Rows[i].Cells[0].Paragraphs.FirstOrDefault().Append(record.Description); var formattedDate = $"{record.StartDate.ToShortDateString()} - {record.EndDate.ToShortDateString()}"; actionsTable.Rows[i].Cells[1].Paragraphs.FirstOrDefault() .Append(formattedDate).Alignment = Alignment.center; actionsTable.Rows[i].Cells[2].Paragraphs.FirstOrDefault() .Append(record.Rate).Alignment = Alignment.right; actionsTable.Rows[i].Cells[3].Paragraphs.FirstOrDefault() .Append($"{record.AmountSign} {record.Amount.ToString("0.00")}").Alignment = Alignment.right; i++; } } var total = $"{_dataModel.Actions.FirstOrDefault().AmountSign} {_dataModel.Actions.Sum(x => x.Amount).ToString("0.00")}"; var totalCell = actionsTable.Rows.LastOrDefault().Cells[3]; var totalWord = actionsTable.Rows.LastOrDefault().Cells[2]; totalWord.VerticalAlignment = VerticalAlignment.Center; totalWord.Paragraphs.FirstOrDefault().Append("TOTAL").Font(CalibriFont).FontSize(8).Alignment = Alignment.right; totalCell.VerticalAlignment = VerticalAlignment.Center; totalCell.SetBorder(TableCellBorderType.Left, new Border { Size = BorderSize.one }); totalCell.SetBorder(TableCellBorderType.Right, new Border { Size = BorderSize.one }); totalCell.SetBorder(TableCellBorderType.Bottom, new Border { Size = BorderSize.one }); totalCell.Paragraphs.FirstOrDefault().Append(total).Alignment = Alignment.right; actionsParagraph.InsertTableAfterSelf(actionsTable); Paragraph emptyParagraph3 = doc.InsertParagraph(); emptyParagraph3.AppendLine(); Paragraph noteParagraph = doc.InsertParagraph(); noteParagraph.Append($"NOTES: {_dataModel.Notes}") .Font(CalibriFont).FontSize(9).Alignment = Alignment.left; noteParagraph.AppendLine(); noteParagraph.AppendLine(); Paragraph thankYouParagraph = doc.InsertParagraph(); thankYouParagraph.AppendLine(); thankYouParagraph.Append("THANK YOU FOR YOUR BUSINESS!") .Font(CalibriFont).FontSize(8).Bold().Alignment = Alignment.center; doc.SaveAs(filePath); doc.Dispose(); }
/// <summary> /// Create an output document and fill in /// its content. /// /// Return 1 if file written, else 0 /// </summary> public int TypeAllRecords() { // Don't do anything unless there are records to write if (this.ItemList.Count == 0) { return(0); } string fn = Path.GetFileName(this.GetOutputFileSpec()); int retInt; this.Worker.ReportProgress(0, string.Format(Properties.Resources.CountWritingMsg, this.ItemList.Count, "labels", fn) ); DocX doc = null; try { doc = this.OpenDocument(); doc.PageLayout.Orientation = this.Orientation; doc.PageWidth = this.PageWidth; doc.PageHeight = this.PageHeight; doc.PageLayout.Orientation = this.Orientation; this.SetMargins(doc); // Add a table with one row and correct # of columns, // but do not insert it into the document yet. this.table = doc.AddTable(1, this.TotalNumberOfColumns); this.table.Alignment = Alignment.center; // Get a reference to the table's first row: Row current_row = this.table.Rows[0]; // Set its properties: SetLabelRowHeight(current_row); SetRowProperties(current_row); if (this.NeedPaddingRow()) { this.AddPaddingRow(); } // Loop through records. "Type" each record's // contents into the next label cell, starting // with the first cell in the first (and so far // the only) row. Add new rows as needed. int col_idx = 0; foreach (object item in this.ItemList) { // End of this row? If so, add // a new row and go to left-hand cell. if (col_idx == this.TotalNumberOfColumns) { // Set current row reference set // to table's new last label row: current_row = this.AddLabelRow(); col_idx = 0; } // Padding cell? Don't write this record into it -- instead, // do anything appropriate for padding cells (might // well be nothing) and skip to next cell. if (this.IsPaddingCell(col_idx)) { this.DoSpace(current_row.Cells[col_idx]); col_idx++; } // Put this record's contents into this cell and // go to next cell. this.TypeOneRecord(current_row.Cells[col_idx], item); col_idx++; } // Set table's column widths BEFORE // inserting the table into the document: this.SetColumnWidths(); doc.InsertTable(this.table); doc.Save(); this.Worker.ReportProgress(0, string.Format(Properties.Resources.FileCreationSuccessMsg, fn) ); retInt = 1; } catch (Exception e) { StringBuilder sb = new StringBuilder(); sb.AppendFormat( Properties.Resources.FileExceptionErrorMsg, fn, e.Message, e.StackTrace ); this.Worker.ReportProgress(0, sb.ToString()); retInt = 0; } finally { doc.Dispose(); } return(retInt); }
private string makeDocument(mainForm.docTypes docType, string numberDoc, string dep, string createDate, List <List <string> > data, string pathToTemplate, string docName = null) { // Если docName = null, то к шаблону добавляется текущая дата - это название рапорта. // возвращает путь, по которому сохранен документ DocX document = DocX.Load(pathToTemplate); if (docType == mainForm.docTypes.vedomost) { document.Paragraphs[2].Append(numberDoc).FontSize(14). Font("Times New Roman").UnderlineStyle(UnderlineStyle.singleLine).Bold(true); document.Paragraphs[3].Append(dep).FontSize(14). Font("Times New Roman").UnderlineStyle(UnderlineStyle.singleLine).Bold(true); document.Paragraphs[4].Append(createDate).FontSize(14). Font("Times New Roman").UnderlineStyle(UnderlineStyle.singleLine).Bold(true); } if (docType == mainForm.docTypes.analysis) { document.Paragraphs[1].Append(dep).FontSize(14). Font("Times New Roman").UnderlineStyle(UnderlineStyle.singleLine).Bold(true); document.Paragraphs[2].Append(createDate).FontSize(14). Font("Times New Roman").UnderlineStyle(UnderlineStyle.singleLine).Bold(true); document.Paragraphs[3].Append(numberDoc).FontSize(14). Font("Times New Roman").UnderlineStyle(UnderlineStyle.singleLine).Bold(true); } if (docType == mainForm.docTypes.report) { document.Paragraphs[0].Append(createDate).FontSize(14). Font("Times New Roman").UnderlineStyle(UnderlineStyle.singleLine).Bold(true); document.Paragraphs[1].Append(numberDoc).FontSize(14). Font("Times New Roman").UnderlineStyle(UnderlineStyle.singleLine).Bold(true); document.Paragraphs[2].Append(dep).FontSize(14). Font("Times New Roman").UnderlineStyle(UnderlineStyle.singleLine).Bold(true); } if (docType == mainForm.docTypes.balances) { document.Paragraphs[2].Append(dep).FontSize(14). Font("Times New Roman").UnderlineStyle(UnderlineStyle.singleLine).Bold(true); document.Paragraphs[3].Append(createDate).FontSize(14). Font("Times New Roman").UnderlineStyle(UnderlineStyle.singleLine).Bold(true); } Table tableinDoc = document.Tables[0]; for (int i = 0; i < data.Count; i++) { tableinDoc.InsertRow(); for (int j = 0; j < data[i].Count; j++) { tableinDoc.Rows[i + 1].Cells[j].Paragraphs[0].Append(data[i][j]).FontSize(14). Font("Times New Roman"); } } if (docName == null) { string path = pathToTemplate.Substring(0, pathToTemplate.Length - 5) + DateTime.Now.ToString().Replace(":", "-") + ".docx"; document.SaveAs(path); document.Dispose(); return(path); } else { document.SaveAs(docName); document.Dispose(); return(docName); } }
public void Dispose() { document.Dispose(); }
/// <summary> /// Gera certificado para todos os alunos que tiverem 100% de presença no evento /// </summary> /// <param name="idEvento">evento desejado</param> /// <returns></returns> public static bool GeraCertificado(int idEvento) { AlunoRepository ar = new AlunoRepository(); Evento ev = eventoRepository.GetEventoById(idEvento); bool flag = true; string templatePath = caminhoTemplates + "template-certificado.docx"; //caminhoDoTemplate List <Documento> certificadosDoc = new List <Documento>(); var template = new FileStream(templatePath, FileMode.Open, FileAccess.Read); List <Aluno> alunos = eventoRepository.GetAlunosPresentes(ev); //alunos com presença foreach (Aluno al in alunos) { string curso = al.AlunoCurso.Select(x => x.Curso.Nome).FirstOrDefault().ToString(); string novoArquivo = CriaDiretorio(new string[] { curso, al.IdAluno.ToString(), "Certificado" }); novoArquivo = novoArquivo + "(" + al.IdUsuario + ") " + ev.IdEvento + " - " + "temp" + ev.NomeEvento + ".docx"; Documento documento = new Documento(); TipoDocumento tipoDoc = tipoDocumentoRepository.GetTipoDoc("Certificado"); documento.IdTipoDoc = tipoDoc.IdTipoDoc; documento.NomeDocumento = "(" + al.IdUsuario + ") " + ev.IdEvento + " - " + "temp" + ev.NomeEvento + ".pdf"; documento.Data = DateTime.Now; documento.IdAlunoCurso = al.AlunoCurso.Select(x => x.IdAlunoCurso).FirstOrDefault(); documento.IdEvento = ev.IdEvento; if (File.Exists(Path.ChangeExtension(novoArquivo, ".pdf"))) { // certificadosDoc.Add(documento); } else { { #region substitui informaçoes seguindo a template DocX doc = DocX.Create(novoArquivo); doc.ApplyTemplate(template, true); if (doc.Text.Contains("<NOME>")) { doc.ReplaceText("<NOME>", al.Usuario.Nome); } if (doc.Text.Contains("<EVENTO>")) { doc.ReplaceText("<EVENTO>", ev.NomeEvento); } if (doc.Text.Contains("<HORAS>")) { doc.ReplaceText("<HORAS>", ev.CargaHoraria.ToString()); } if (doc.Text.Contains("<DIA>")) { doc.ReplaceText("<DIA>", DateTime.Now.Day.ToString()); } if (doc.Text.Contains("<MES>")) { string mes = DateTime.Now.ToString("MMMM", CultureInfo.CreateSpecificCulture("pt-BR")); doc.ReplaceText("<MES>", mes); } if (doc.Text.Contains("<ANO>")) { doc.ReplaceText("<ANO>", DateTime.Now.Year.ToString()); } doc.Save(); doc.Dispose(); Document pdf = new Document(); pdf.LoadFromFile(novoArquivo); File.Delete(novoArquivo); novoArquivo = Path.ChangeExtension(novoArquivo, ".pdf"); pdf.SaveToFile(novoArquivo, FileFormat.PDF); } #region criptografa certificado try { string caminhonovo = novoArquivo.Replace("temp", ""); FileStream fs = new FileStream(caminhonovo, FileMode.Create); byte[] arquivo = File.ReadAllBytes(novoArquivo); File.Delete(novoArquivo); RijndaelManaged rmCryp = new RijndaelManaged(); CryptoStream cs = new CryptoStream(fs, rmCryp.CreateEncryptor(Key, Key), CryptoStreamMode.Write); foreach (var data in arquivo) { cs.WriteByte((byte)data); } cs.Close(); fs.Close(); documento.CaminhoDocumento = caminhonovo; certificadosDoc.Add(documento); ar.AdicionaHoras(ev.CargaHoraria, al.IdAluno, ev.IdEvento); } catch (Exception e) { flag = false; } #endregion #endregion } } if (!documentoRepository.PersisteCertificados(certificadosDoc)) { flag = false; } else { } return(flag); }
//首席 //public string Addchiefsupervisordata(WordTableInfo Info) //{ // Common.Common.load_cheif_supervisor(); // object missingValue = System.Reflection.Missing.Value; // object myTrue = false; //不显示Word窗口 // object fileName = Environment.CurrentDirectory + "\\" + "chief_supervisor.doc";//WORD文档所在路径 // string newfile = Common.Common.strAddfilesPath + Info.Teacher + Info.Time.Trim() + Info.Supervisor + ".doc";//存储路径名称 // // object fileName1 = Environment.CurrentDirectory + "\\" + "supervisor.doc"; // Microsoft.Office.Interop.Word._Application oWord = new Microsoft.Office.Interop.Word.Application(); // Microsoft.Office.Interop.Word._Document oDoc; // oDoc = oWord.Documents.Open(ref fileName, ref missingValue, // ref myTrue, ref missingValue, ref missingValue, ref missingValue, // ref missingValue, ref missingValue, ref missingValue, // ref missingValue, ref missingValue, ref missingValue, // ref missingValue, ref missingValue, ref missingValue, // ref missingValue); // Microsoft.Office.Interop.Word.Table newtable = oDoc.Tables[1];//获取word文档中的表格 // newtable.Cell(1, 2).Range.Text = Info.Teacher; // newtable.Cell(1, 6).Range.Text = Info.Time.Substring(0, Info.Time.IndexOf(" ")); // newtable.Cell(2, 6).Range.Text = Info.Classroom + Info.Time.Substring(Info.Time.IndexOf(" ") + 1); // newtable.Cell(4, 2).Range.Text = Info.Class; // newtable.Cell(5, 2).Range.Text = Info.Subject; // object bSaveChange = true; // oDoc.Close(ref bSaveChange, ref missingValue, ref missingValue); // oDoc = null; // oWord = null; // closefile(); // if (!System.IO.File.Exists(Common.Common.strAddfilesPath)) // { // Directory.CreateDirectory(Common.Common.strAddfilesPath); // } // System.IO.File.Copy(fileName.ToString(), newfile, true); // File.Delete(fileName.ToString()); // //sent_email(Supervisor, Time, Subject, newfile); // //movetofile(newfile); // return newfile; //} ////一般 //public string fullcheifsupervisor(WordTableInfo Info) //{ // Common.Common.load_cheif_supervisor(); // string fileName = Environment.CurrentDirectory + "\\" + "chief_supervisor.doc";//WORD文档所在路径 // string newfile = Common.Common.strAddfilesPath + Info.Teacher + Info.Time.Trim() + Info.Supervisor + ".doc";//存储路径名称 // DocX doc = DocX.Load(fileName); // Table table = doc.Tables[0]; // table.Rows[0].Cells[1].Paragraphs[0].ReplaceText("teacher", Info.Teacher); // table.Rows[0].Cells[5].Paragraphs[0].ReplaceText("time", Info.Time.Substring(0, Info.Time.IndexOf(" "))); // table.Rows[1].Cells[5].Paragraphs[0].ReplaceText("address", Info.Classroom + Info.Time.Substring(Info.Time.IndexOf(" ") + 1)); // table.Rows[3].Cells[1].Paragraphs[0].ReplaceText("class", Info.Class); // table.Rows[4].Cells[1].Paragraphs[0].ReplaceText("context", Info.Subject); // if (!System.IO.File.Exists(Common.Common.strAddfilesPath)) // { // Directory.CreateDirectory(Common.Common.strAddfilesPath); // } // doc.SaveAs(newfile); // doc.Dispose(); // return newfile; //} //public string fullsupervisor(WordTableInfo Info) //{ // Common.Common.load_supervisor(); // string fileName1 = Environment.CurrentDirectory + "\\" + "supervisor.doc"; // string newfile = Common.Common.strAddfilesPath + "\\" + Info.Teacher + Info.Time.Trim() + Info.Supervisor + ".doc"; // DocX doc = DocX.Load(fileName1); // doc.ReplaceText("title", "广东医学院教师课堂教学质量评价表" + "(" + Info.Teachingtype + ")"); // Table table = doc.Tables[0]; // table.Rows[0].Cells[1].Paragraphs[0].ReplaceText("Teacher", Info.Teacher); // table.Rows[0].Cells[3].Paragraphs[0].ReplaceText("Perfession", Info.Perfession); // table.Rows[0].Cells[5].Paragraphs[0].ReplaceText("Time", Info.Time.Substring(0, Info.Time.IndexOf(" "))); // table.Rows[1].Cells[1].Paragraphs[0].ReplaceText("Class", Info.Class); // table.Rows[1].Cells[3].Paragraphs[0].ReplaceText("address", Info.Classroom + Info.Time.Substring(Info.Time.IndexOf(" ") + 1)); // table.Rows[2].Cells[1].Paragraphs[0].ReplaceText("Context", Info.Subject); // if (!System.IO.File.Exists(Common.Common.strAddfilesPath)) // { // Directory.CreateDirectory(Common.Common.strAddfilesPath); // } // doc.SaveAs(newfile); // doc.Dispose(); // return newfile; //} /// <summary> /// 将对象数组写入word文档 /// </summary> /// <param name="info">对象数组</param> public string fullclasses(List <ExportClassModel> info, string classespath, string wordpath) { Common.load_classes(wordpath); //加载输出word文档,可以在resource文件中查看 string fileName1 = wordpath; //输出目录 string newfile = classespath; //保存目录 DocX doc = DocX.Load(fileName1); //用第三方类库加载word文档 //去除表格中的数字 for (int i = 0; i < doc.Tables.Count; i++) { Table tb = doc.Tables[i]; for (int column = 2; column < 7; column++) { for (int row = 1; row < 12; row++) { string text = tb.Rows[row].Cells[column].Paragraphs[0].Text; if (IsNumber(text)) { tb.Rows[row].Cells[column].Paragraphs[0].ReplaceText(text, ""); } } } } for (int i = 0; i < info.Count; i++) { Table tb = doc.Tables[info[i].Week - 1]; //word文档总共有表格20张,例如:现在是第一周,那么就是第一张表,索引从0开始 //通过表格原有的数字,确定替换位置,例如:现在是第1周,星期1,第1-2节,那么对应的表格位置就是第2行,第2列,仔细看resource中的表格 if (info[i].Start < 10) //上下午 { tb.Rows[info[i].Start].Cells[1 + info[i].Day].Paragraphs[0].AppendLine(info[i].Teachername + ":" + info[i].Classname + "(" + info[i].Classtype + ")"); tb.Rows[info[i].End].Cells[1 + info[i].Day].Paragraphs[0].AppendLine(info[i].Teachername + ":" + info[i].Classname + "(" + info[i].Classtype + ")"); if (info[i].IsOverTop) { for (int k = info[i].Start + 1; k < info[i].End; k++) { tb.Rows[k].Cells[1 + info[i].Day].Paragraphs[0].AppendLine(info[i].Teachername + ":" + info[i].Classname + "(" + info[i].Classtype + ")"); } } } else//晚上 { tb.Rows[info[i].Start].Cells[1 + info[i].Day].Paragraphs[0].AppendLine(info[i].Teachername + ":" + info[i].Classname + "(" + info[i].Classtype + ")"); if (info[i].IsOverTop) { for (int k = info[i].Start + 1; k < info[i].End; k++) { tb.Rows[k].Cells[1 + info[i].Day].Paragraphs[0].AppendLine(info[i].Teachername + ":" + info[i].Classname + "(" + info[i].Classtype + ")"); } } } } //if (!File.Exists(classespath)) //{ // Directory.CreateDirectory(classespath); //} try { doc.SaveAs(newfile); //保存 doc.Dispose(); //释放对象 //MessageBox.Show("导出成功"); return("导出成功"); } //catch (IOException) //{ // //MessageBox.Show("当前文件正在打开,请关闭后重试"); // return "当前文件正在打开,请关闭后重试"; //} catch (Exception e) { //MessageBox.Show(e.ToString()); return(e.ToString()); } }
public void Parse(Stream input, Object data, ParseOptions options = null) { if (options == null) { options = new ParseOptions(); } using (DocX document = DocX.Load(input)) { //do loop replace first to avoid variable confusion //get a list of all loop variables var loopsToReplace = document.FindUniqueByPattern(options.LoopVariable.Regex, System.Text.RegularExpressions.RegexOptions.Multiline); foreach (var loop in loopsToReplace) { var loopListName = loop.Replace(options.LoopVariable.Start, string.Empty).Replace(options.LoopVariable.End, string.Empty); var loopData = GetPropValue(data, loopListName) as IEnumerable <Object>; if (loopData != null) { var table = document.Tables.Where(z => z.Rows.Any(r => r.Cells.Any(c => c.Xml.Value.Contains(loop)))).FirstOrDefault(); if (table != null) { var row = table.Rows.FirstOrDefault(r => r.Cells.Any(c => c.Xml.Value.Contains(loop))); var index = table.Rows.FindIndex((r => r.Cells.Any(c => c.Xml.Value.Contains(loop)))); row.ReplaceText(loop, ""); if (table.Rows.Count == 1) { table.InsertRow(); // insert row doesn't work when table has zero rows. We add 1 row and remove the original template row if there is only 1 row in total } table.RemoveRow(index); int rowNumber = 1; foreach (var rowData in loopData) { var newRow = table.InsertRow(row, index); foreach (var cell in newRow.Cells) { var cellValue = cell.Xml.Value; var variables = Regex.Matches(cellValue, options.Variable.Regex, RegexOptions.Multiline); foreach (var variable in variables) { var variableName = variable.ToString().Replace(options.Variable.Start, string.Empty).Replace(options.Variable.End, string.Empty); var cellData = variableName == options.RowNumberVariable ? rowNumber : rowData.GetPropValue(variableName); cell.ReplaceText(variable.ToString(), cellData?.ToString() ?? ""); } } rowNumber++; index++; } } } } //replace variables var variablesToReplace = document.FindUniqueByPattern(options.Variable.Regex, System.Text.RegularExpressions.RegexOptions.Multiline); foreach (var variable in variablesToReplace) { var variableName = variable.Replace(options.Variable.Start, string.Empty).Replace(options.Variable.End, string.Empty); var cellData = GetPropValue(data, variableName); document.ReplaceText(variable.ToString(), cellData?.ToString() ?? ""); } //end of variable replace document.Save(); document.Dispose(); } }