public void GenerarArchivoDocxDesdeTextosHtml(string[] textosHtml, System.IO.Stream archivo) { using (DocumentFormat.OpenXml.Packaging.WordprocessingDocument objPaquete = DocumentFormat.OpenXml.Packaging.WordprocessingDocument.Create(archivo, DocumentFormat.OpenXml.WordprocessingDocumentType.Document)) { DocumentFormat.OpenXml.Packaging.MainDocumentPart objDocumentoPrincipal = objPaquete.MainDocumentPart; if (objDocumentoPrincipal == null) { objDocumentoPrincipal = objPaquete.AddMainDocumentPart(); new DocumentFormat.OpenXml.Wordprocessing.Document(new DocumentFormat.OpenXml.Wordprocessing.Body()).Save(objDocumentoPrincipal); } NotesFor.HtmlToOpenXml.HtmlConverter objConversorHtml = new NotesFor.HtmlToOpenXml.HtmlConverter(objDocumentoPrincipal); DocumentFormat.OpenXml.Wordprocessing.Body objCuerpo = objDocumentoPrincipal.Document.Body; objConversorHtml.ImageProcessing = NotesFor.HtmlToOpenXml.ImageProcessing.ManualProvisioning; objConversorHtml.ProvisionImage += eventoHtmlDoc_ProveerImagenes; for (int intIndiceHtml = 0; intIndiceHtml < textosHtml.Length; intIndiceHtml++) { if (intIndiceHtml > 0) { Paragraph PageBreakParagraph = new Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Break() { Type = BreakValues.Page })); objCuerpo.Append(PageBreakParagraph); } var arrParrafos = objConversorHtml.Parse(textosHtml[intIndiceHtml]); foreach (var objParrafo in arrParrafos) { objCuerpo.Append(objParrafo); } } objDocumentoPrincipal.Document.Save(); } }
public override void Write() { ExportFileName = PopulatedName(ExportFileName); if (!String.IsNullOrWhiteSpace(ExportFileName)) { DocProperties["FileName"] = ExportFileName; DocProperties["TableCount"] = _dataSet.Tables.Count.ToString(); if (PopulatePropertiesOnly) { if (_dataSet != null) { foreach (DataTable dTable in _dataSet.Tables) { if (dTable.Rows.Count > 0) { foreach (DataColumn dColumn in dTable.Columns) { DocProperties[dColumn.ColumnName] = dTable.Rows[0][dColumn].ToString(); } } } } } switch (DestinationType) { case OfficeFileType.WordDocument: WordprocessingDocument doc; if (File.Exists(TemplateFileName)) { doc = WordprocessingDocument.CreateFromTemplate(TemplateFileName); doc = (WordprocessingDocument)doc.SaveAs(ExportFileName); } else { doc = WordprocessingDocument.Create(ExportFileName, WordprocessingDocumentType.Document); } CustomFilePropertiesPart customProp = doc.CustomFilePropertiesPart; if (customProp == null) { customProp = doc.AddCustomFilePropertiesPart(); } SetFileProperties(customProp); MainDocumentPart mainDoc = doc.MainDocumentPart; if (mainDoc == null) { mainDoc = doc.AddMainDocumentPart(); } DocumentSettingsPart settingsPart = mainDoc.GetPartsOfType <DocumentSettingsPart>().First(); UpdateFieldsOnOpen updateFields = new UpdateFieldsOnOpen { Val = new OnOffValue(true) }; settingsPart.Settings.PrependChild <UpdateFieldsOnOpen>(updateFields); settingsPart.Settings.Save(); if (!PopulatePropertiesOnly) { if (mainDoc.Document == null) { mainDoc.Document = new word.Document(); } word.Body body = new word.Body(); bool firstTable = true; foreach (DataTable dt in _dataSet.Tables) { if (!firstTable) { body.Append(GetPageBreak()); } else { firstTable = false; } body.Append(GetParagraph(dt.TableName)); body.Append(GetWordTable(dt)); } mainDoc.Document.Append(body); } mainDoc.Document.Save(); doc.Dispose(); break; case OfficeFileType.ExcelWorkbook: SpreadsheetDocument spreadSheet; if (File.Exists(TemplateFileName)) { spreadSheet = SpreadsheetDocument.CreateFromTemplate(TemplateFileName); spreadSheet = (SpreadsheetDocument)spreadSheet.SaveAs(ExportFileName); } else { spreadSheet = SpreadsheetDocument.Create(ExportFileName, SpreadsheetDocumentType.Workbook); spreadSheet.Save(); } using (SpreadsheetDocument workbook = spreadSheet) { CustomFilePropertiesPart excelCustomProp = workbook.AddCustomFilePropertiesPart(); SetFileProperties(excelCustomProp); if (workbook.WorkbookPart == null) { workbook.AddWorkbookPart(); } if (workbook.WorkbookPart.Workbook == null) { workbook.WorkbookPart.Workbook = new excel.Workbook(); } if (workbook.WorkbookPart.Workbook.Sheets == null) { workbook.WorkbookPart.Workbook.Sheets = new excel.Sheets(); } excel.Sheets sheets = workbook.WorkbookPart.Workbook.Sheets; foreach (DataTable table in _dataSet.Tables) { excel.SheetData sheetData = null; WorksheetPart sheetPart = null; excel.Sheet sheet = null; foreach (OpenXmlElement element in sheets.Elements()) { if (element is Sheet) { sheet = (Sheet)element; if (sheet.Name.Value.Equals(table.TableName, StringComparison.CurrentCultureIgnoreCase)) { //Assign the sheetPart sheetPart = (WorksheetPart)workbook.WorkbookPart.GetPartById(sheet.Id.Value); sheetData = sheetPart.Worksheet.GetFirstChild <SheetData>(); break; } } sheet = null; } if (sheet == null) { sheetPart = workbook.WorkbookPart.AddNewPart <WorksheetPart>(); //Create a new WorksheetPart sheetData = new excel.SheetData(); //create a new SheetData sheetPart.Worksheet = new excel.Worksheet(sheetData); /// Create a new Worksheet with the sheetData and link it to the sheetPart... string relationshipId = workbook.WorkbookPart.GetIdOfPart(sheetPart); //get the ID of the sheetPart. sheet = new excel.Sheet() { Id = relationshipId, SheetId = 1, Name = table.TableName }; //create a new sheet sheets.Append(sheet); //append the sheet to the sheets. } List <String> columns = new List <string>(); foreach (System.Data.DataColumn column in table.Columns) { columns.Add(column.ColumnName); } if (PrintTableHeader) { excel.Row headerRow = new excel.Row(); foreach (string column in columns) { excel.Cell cell = new excel.Cell { DataType = excel.CellValues.String, CellValue = new excel.CellValue(GetColumnName(table.Columns[column])) }; headerRow.AppendChild(cell); } sheetData.AppendChild(headerRow); } foreach (DataRow dsrow in table.Rows) { excel.Row newRow = new excel.Row(); foreach (String col in columns) { excel.Cell cell = new excel.Cell { DataType = excel.CellValues.String, CellValue = new excel.CellValue(dsrow[col].ToString()) // }; newRow.AppendChild(cell); } sheetData.AppendChild(newRow); } sheetPart.Worksheet.Save(); } workbook.WorkbookPart.Workbook.Save(); workbook.Save(); workbook.Close(); } break; } } }
public void TableToWord(Wordprocessing.Table table, WordprocessingDocument document) { Wordprocessing.Body body = new Wordprocessing.Body(); Wordprocessing.Paragraph paragraph = new Wordprocessing.Paragraph(); body.Append(table); body.Append(paragraph); document.MainDocumentPart.Document.AppendChild(body); document.MainDocumentPart.Document.Save(); document.Close(); }
public Wordprocessing.Body insertinform() { Wordprocessing.Body body = new Wordprocessing.Body(); //Параграф1 Wordprocessing.Paragraph paragraph1 = new Wordprocessing.Paragraph(); Wordprocessing.ParagraphProperties paragraphProperties1 = new Wordprocessing.ParagraphProperties(); Wordprocessing.SpacingBetweenLines spacingBetweenLines1 = new Wordprocessing.SpacingBetweenLines() { After = "0" }; Wordprocessing.Justification justification1 = new Wordprocessing.Justification() { Val = Wordprocessing.JustificationValues.Center }; paragraphProperties1.Append(spacingBetweenLines1); paragraphProperties1.Append(justification1); Wordprocessing.Run run1 = new Wordprocessing.Run(); Wordprocessing.RunProperties runProperties1 = new Wordprocessing.RunProperties(); Wordprocessing.RunFonts runFonts2 = new Wordprocessing.RunFonts() { Ascii = "Times New Roman", HighAnsi = "Times New Roman", ComplexScript = "Times New Roman" }; Wordprocessing.Bold bold2 = new Wordprocessing.Bold(); Wordprocessing.FontSize fontSize2 = new Wordprocessing.FontSize() { Val = "24" }; runProperties1.Append(runFonts2); runProperties1.Append(bold2); runProperties1.Append(fontSize2); Wordprocessing.Text text1 = new Wordprocessing.Text(); text1.Text = "ФГБОУВПО \"ПЕРМСКИЙ ГОСУДАРСТВЕННЫЙ НАЦИОНАЛЬНЫЙ ИССЛЕДОВАТЕЛЬСКИЙ УНИВЕРСИТЕТ\""; run1.Append(runProperties1); run1.Append(text1); paragraph1.Append(paragraphProperties1); paragraph1.Append(run1); //Параграф2 Wordprocessing.Paragraph paragraph2 = new Wordprocessing.Paragraph(); Wordprocessing.ParagraphProperties paragraphProperties2 = new Wordprocessing.ParagraphProperties(); Wordprocessing.SpacingBetweenLines spacingBetweenLines2 = new Wordprocessing.SpacingBetweenLines() { After = "0" }; Wordprocessing.Justification justification2 = new Wordprocessing.Justification() { Val = Wordprocessing.JustificationValues.Center }; paragraphProperties2.Append(spacingBetweenLines2); paragraphProperties2.Append(justification2); Wordprocessing.Run run2 = new Wordprocessing.Run(); Wordprocessing.RunProperties runProperties2 = new Wordprocessing.RunProperties(); Wordprocessing.RunFonts runFonts4 = new Wordprocessing.RunFonts() { Ascii = "Times New Roman", HighAnsi = "Times New Roman", ComplexScript = "Times New Roman" }; Wordprocessing.FontSize fontSize4 = new Wordprocessing.FontSize() { Val = "24" }; runProperties2.Append(runFonts4); runProperties2.Append(fontSize4); Wordprocessing.Text text2 = new Wordprocessing.Text(); text2.Text = "Механико-математический факультет "; run2.Append(runProperties2); run2.Append(text2); Wordprocessing.Run run3 = new Wordprocessing.Run(); Wordprocessing.RunProperties runProperties3 = new Wordprocessing.RunProperties(); Wordprocessing.RunFonts runFonts5 = new Wordprocessing.RunFonts() { Ascii = "Times New Roman", HighAnsi = "Times New Roman", ComplexScript = "Times New Roman" }; Wordprocessing.FontSize fontSize5 = new Wordprocessing.FontSize() { Val = "24" }; runProperties3.Append(runFonts5); runProperties3.Append(fontSize5); Wordprocessing.Break break1 = new Wordprocessing.Break(); Wordprocessing.Text text3 = new Wordprocessing.Text(); text3.Text = "очная форма обучения"; run3.Append(runProperties3); run3.Append(break1); run3.Append(text3); paragraph2.Append(paragraphProperties2); paragraph2.Append(run2); paragraph2.Append(run3); //Параграф2 Wordprocessing.Paragraph paragraph3 = new Wordprocessing.Paragraph() { RsidParagraphAddition = "004D49E1", RsidParagraphProperties = "004D49E1", RsidRunAdditionDefault = "004D49E1" }; Wordprocessing.ParagraphProperties paragraphProperties3 = new Wordprocessing.ParagraphProperties(); Wordprocessing.SpacingBetweenLines spacingBetweenLines3 = new Wordprocessing.SpacingBetweenLines() { After = "0" }; Wordprocessing.Justification justification3 = new Wordprocessing.Justification() { Val = Wordprocessing.JustificationValues.Center }; paragraphProperties3.Append(spacingBetweenLines3); paragraphProperties3.Append(justification3); Wordprocessing.Run run4 = new Wordprocessing.Run(); Wordprocessing.RunProperties runProperties4 = new Wordprocessing.RunProperties(); Wordprocessing.RunFonts runFonts7 = new Wordprocessing.RunFonts() { Ascii = "Times New Roman", HighAnsi = "Times New Roman", ComplexScript = "Times New Roman" }; Wordprocessing.Bold bold4 = new Wordprocessing.Bold(); runProperties4.Append(runFonts7); runProperties4.Append(bold4); Wordprocessing.Text text4 = new Wordprocessing.Text(); text4.Text = "ЭКЗАМЕНАЦИОННАЯ ВЕДОМОСТЬ"; run4.Append(runProperties4); run4.Append(text4); Wordprocessing.Run run5 = new Wordprocessing.Run(); Wordprocessing.Break break2 = new Wordprocessing.Break(); run5.Append(break2); paragraph3.Append(paragraphProperties3); paragraph3.Append(run4); paragraph3.Append(run5); body.Append(paragraph1); body.Append(paragraph2); body.Append(paragraph3); return body; }
public void CreateWordDoc(DataTable data, decimal t, string user) { string pathUser = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); string pathDownload = Path.Combine(pathUser, "Downloads"); //string pathDownload = Server.MapPath("~/Content/"); decimal total = t; try { //Set the current directory. Directory.SetCurrentDirectory(pathDownload); } catch (DirectoryNotFoundException e) { Console.WriteLine("The specified directory does not exist. {0}", e); } WordprocessingDocument doc = WordprocessingDocument.Create("ExpenseReport.docx", WordprocessingDocumentType.Document); MainDocumentPart mainDocPart = doc.AddMainDocumentPart(); mainDocPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document(); DocumentFormat.OpenXml.Wordprocessing.Body body = new DocumentFormat.OpenXml.Wordprocessing.Body(); mainDocPart.Document.Append(body); DocumentFormat.OpenXml.Wordprocessing.Table table = new DocumentFormat.OpenXml.Wordprocessing.Table(); //border TableProperties tblProp = new TableProperties( new TableBorders( new InsideHorizontalBorder() { Val = new EnumValue <BorderValues>(BorderValues.BasicThinLines), Size = 10 }) ); // Append the TableProperties object to the empty table. table.AppendChild <TableProperties>(tblProp); //setting header DocumentFormat.OpenXml.Wordprocessing.TableRow tr = new DocumentFormat.OpenXml.Wordprocessing.TableRow(); DocumentFormat.OpenXml.Wordprocessing.RunProperties rp = new DocumentFormat.OpenXml.Wordprocessing.RunProperties(); rp.Append(new DocumentFormat.OpenXml.Wordprocessing.Color() { Val = "#FF0000" }); RunFonts rFont1 = new RunFonts(); rFont1.Ascii = "Arial"; rp.Append(rFont1); rp.Append(new Bold()); rp.Append(new DocumentFormat.OpenXml.Wordprocessing.FontSize() { Val = "28" }); DocumentFormat.OpenXml.Wordprocessing.Run run = new DocumentFormat.OpenXml.Wordprocessing.Run(); run.RunProperties = rp; run.Append(new Text("Expense Report for " + user)); DocumentFormat.OpenXml.Wordprocessing.Paragraph para = new DocumentFormat.OpenXml.Wordprocessing.Paragraph(run); DocumentFormat.OpenXml.Wordprocessing.TableCellProperties tcpp = new DocumentFormat.OpenXml.Wordprocessing.TableCellProperties(); tcpp.Append(new DocumentFormat.OpenXml.Wordprocessing.TableCellWidth { Type = DocumentFormat.OpenXml.Wordprocessing.TableWidthUnitValues.Dxa, Width = "2200" }); GridSpan gs = new GridSpan(); gs.Val = 5; tcpp.Append(gs); DocumentFormat.OpenXml.Wordprocessing.TableCell tc = new DocumentFormat.OpenXml.Wordprocessing.TableCell(tcpp, para); tr.Append(tc); table.Append(tr); DocumentFormat.OpenXml.Wordprocessing.TableRow row_header = new DocumentFormat.OpenXml.Wordprocessing.TableRow(); foreach (DataColumn column in data.Columns) { DocumentFormat.OpenXml.Wordprocessing.TableCell cell = new DocumentFormat.OpenXml.Wordprocessing.TableCell(); cell.Append(new DocumentFormat.OpenXml.Wordprocessing.Paragraph( new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Text(column.ToString())))); cell.Append(new DocumentFormat.OpenXml.Wordprocessing.TableCellProperties(new DocumentFormat.OpenXml.Wordprocessing.TableCellWidth { Type = DocumentFormat.OpenXml.Wordprocessing.TableWidthUnitValues.Dxa, Width = "2200" })); row_header.Append(cell); } table.Append(row_header); for (int i = 0; i < data.Rows.Count; ++i) { DocumentFormat.OpenXml.Wordprocessing.TableRow row = new DocumentFormat.OpenXml.Wordprocessing.TableRow(); for (int j = 0; j < data.Columns.Count; j++) { DocumentFormat.OpenXml.Wordprocessing.TableCell cell = new DocumentFormat.OpenXml.Wordprocessing.TableCell(); cell.Append(new DocumentFormat.OpenXml.Wordprocessing.Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Text(data.Rows[i][j].ToString())))); cell.Append(new DocumentFormat.OpenXml.Wordprocessing.TableCellProperties(new DocumentFormat.OpenXml.Wordprocessing.TableCellWidth { Type = DocumentFormat.OpenXml.Wordprocessing.TableWidthUnitValues.Dxa, Width = "2200" })); row.Append(cell); } table.Append(row); } body.Append(table); Run run1 = new Run(); Paragraph para1 = new Paragraph(run1); run1.AppendChild(new Text("The total Expenditure is " + total)); body.Append(para1); doc.MainDocumentPart.Document.Save(); doc.Dispose(); }
public ActionResult ExportWord() { ExportRetailModel model = Session["@ExportWord@"] as ExportRetailModel; //render view const string viewName = "ViewForWord"; String html = RenderStringView(viewName, model); try { const string filename = "StreamTest.docx"; const string contentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; using (MemoryStream generatedDocument = new MemoryStream()) { using (WordprocessingDocument package = WordprocessingDocument.Create(generatedDocument, WordprocessingDocumentType.Document)) { MainDocumentPart mainPart = package.MainDocumentPart; if (mainPart == null) { mainPart = package.AddMainDocumentPart(); new HtmlDocument.Document(new HtmlDocument.Body()).Save(mainPart); } if (Request.Url != null) { HtmlXml.HtmlConverter converter = new HtmlXml.HtmlConverter(mainPart) { BaseImageUrl = new Uri(Request.Url.Scheme + "://" + Request.Url.Authority) }; HtmlDocument.Body body = mainPart.Document.Body; var paragraphs = converter.Parse(html); foreach (OpenXmlCompositeElement t in paragraphs) { body.Append(t); } } mainPart.Document.Save(); } byte[] bytesInStream = generatedDocument.ToArray(); // simpler way of converting to array generatedDocument.Close(); Response.Clear(); Response.ContentType = contentType; Response.AddHeader("content-disposition", "attachment;filename=" + filename); //this will generate problems Response.BinaryWrite(bytesInStream); try { Response.End(); } catch (Exception ex) { return(new EmptyResult()); //Response.End(); generates an exception. if you don't use it, you get some errors when Word opens the file... } Session.Remove("@ExportWord@"); return(new EmptyResult()); } } catch (Exception ex) { return(new EmptyResult()); } }