I want to set forecolor of the text in the excel document which I open to write the text.
For that I tried :
var stylesheet1 = spreadSheet.WorkbookPart.WorkbookStylesPart.Stylesheet;
Fills fills1 = new Fills() { Count = (UInt32Value)5U };
Fill fill5 = new Fill();
PatternFill patternFill5 = new PatternFill() { PatternType = PatternValues.Solid };
ForegroundColor foregroundColor3 = new ForegroundColor() { Rgb = "#FF0000" };
patternFill5.Append(foregroundColor3);
fill5.Append(patternFill5);
fills1.Append(fill5);
stylesheet1.Fills.Append(fills1);
var fid = stylesheet1.Fills.Count++;
wbsp.Stylesheet = stylesheet1;
Row excelRow;
excelRow = new Row();
excelRow.RowIndex = 0;
Cell cell = new Cell()
{
//create the cell reference of format A1, B2 etc
//CellReference = Convert.ToString(Convert.ToChar(65)),
CellReference = "A1",
DataType = CellValues.String
};
CellValue cellValue = new CellValue();
cellValue.Text = "*";
//add the value to the cell
cell.Append(cellValue);
CellFormat cellFormat = null;
if (cell.StyleIndex.HasValue)
{
var originalCellFormat = spreadSheet.WorkbookPart.WorkbookStylesPart.Stylesheet.CellFormats.ToList()[(int)cell.StyleIndex.Value] as CellFormat;
//copy the original cellformat data to the new cellformat
if (originalCellFormat != null)
{
cellFormat = new CellFormat(originalCellFormat.OuterXml);
}
else
{
cellFormat = new CellFormat();
}
}
else
{
cellFormat = new CellFormat();
}
cellFormat.FillId = (UInt32)fid;
stylesheet1.CellFormats.Append(cellFormat);
var theStyleIndex = stylesheet1.CellFormats.Count++;
cell.StyleIndex = new UInt32Value { Value = (UInt32)theStyleIndex };
spreadSheet.WorkbookPart.WorkbookStylesPart.Stylesheet.Save();
But it gives me error on the first line :
var stylesheet1 = spreadSheet.WorkbookPart.WorkbookStylesPart.Stylesheet;
Error:
Object not set to instance of an object.
When i add a watch on code :
spreadSheet.WorkbookPart.WorkbookStylesPart.Stylesheet;
I find that : spreadSheet.WorkbookPart.WorkbookStylesPart is null
Please help me how can i add forecolor to cell
Perhaps the initialization of SpreadsheetDocument is missing?
using (SpreadsheetDocument document = SpreadsheetDocument.Create(filePath + ".xlsx", SpreadsheetDocumentType.Workbook))
{
WorkbookPart workbookPart = document.AddWorkbookPart();
workbookPart.Workbook = new Workbook();
WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet();
WorkbookStylesPart workStylePart = workbookPart.AddNewPart<WorkbookStylesPart>();
workStylePart.Stylesheet = new Stylesheet();
var stylesheet1 = document.WorkbookPart.WorkbookStylesPart.Stylesheet;
}
Related
My excel file generated by one of my applications, is getting this error
The error is :
“We Found A Problem with Some Content in Excel"
and it points me to a log file with the message:
Repaired recods: View from /xl/worksheets/sheet1.xml part.
Now to my .cs files where they are built:
First, this is how i start the workbook:
using (var spreadSheet = SpreadsheetDocument.Create(excelFilename, SpreadsheetDocumentType.Workbook))
{
var workbookPart = spreadSheet.AddWorkbookPart();
var openXmlExportHelper = new OpenXmlWriterHelper();
openXmlExportHelper.SaveCustomStylesheet(workbookPart);
var wkbook = workbookPart.Workbook = new Workbook();
var sheets = wkbook.AppendChild<Sheets>(new Sheets());
// create worksheet 1
var worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
var sheet = new Sheet() { Id = workbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "Sheet1" };
sheets.Append(sheet);
using (var writer = OpenXmlWriter.Create(worksheetPart))
{
writer.WriteStartElement(new Worksheet());
writer.WriteStartElement(new SheetData());
var headerList = new string[dataTableExcel.Columns.Count];
for (var i = 0; i < dataTableExcel.Columns.Count; i++)
{
headerList[i] = dataTableExcel.Columns[i].ColumnName;
}
//Create header row
writer.WriteStartElement(new Row());
for (int i = 0; i < headerList.Length; i++)
{
//header formatting attribute. This will create a <c> element with s=2 as its attribute
//s stands for styleindex
var attributes = new OpenXmlAttribute[] { new OpenXmlAttribute("s", null, "2") }.ToList();
openXmlExportHelper.WriteCellValueSax(writer, headerList[i], CellValues.SharedString, attributes);
}
writer.WriteEndElement(); //end of Row tag
foreach(var element in lista)
{
writer.WriteStartElement(new Row());
foreach (var campo in element.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
var name = campo.Name;
openXmlExportHelper.WriteCellValueSax(writer, campo.GetValue(element) != null ? campo.GetValue(element).ToString() : string.Empty,
campo.GetValue(element) != null ? RecuperaFormatoCampo(campo.GetValue(element).ToString()) : CellValues.InlineString,null,1,name);
}
writer.WriteEndElement();
}
writer.WriteEndElement(); //end of SheetData
writer.WriteEndElement(); //end of worksheet
writer.Close();
openXmlExportHelper.CreateShareStringPart(workbookPart);
}
}
Important, the savecustomstylesheet has some customizations like the following:
//get a copy of the default excel style sheet then add additional styles to it
var stylesheet = CreateDefaultStylesheet();
// ***************************** Fills *********************************
var fills = stylesheet.Fills;
//header fills background color
var fill = new Fill();
var patternFill = new PatternFill();
patternFill.PatternType = PatternValues.Solid;
patternFill.ForegroundColor = new ForegroundColor { Rgb = HexBinaryValue.FromString("C8EEFF") };
//patternFill.BackgroundColor = new BackgroundColor() { Indexed = 64 };
fill.PatternFill = patternFill;
fills.AppendChild(fill);
fills.Count = (uint)fills.ChildElements.Count;
// *************************** numbering formats ***********************
var nfs = stylesheet.NumberingFormats;
//number less than 164 is reserved by excel for default formats
uint iExcelIndex = 165;
NumberingFormat nf;
nf = new NumberingFormat();
nf.NumberFormatId = iExcelIndex++;
nf.FormatCode = #"[$-409]m/d/yy\ h:mm\ AM/PM;#";
nfs.Append(nf);
NumberingFormat nf2;
nf2 = new NumberingFormat();
nf2.NumberFormatId = iExcelIndex++;
nf2.FormatCode = "\"R$\"#,##0.00;[Red]\"R$\"#,##0.00";
nfs.Append(nf2);
nfs.Count = (uint)nfs.ChildElements.Count;
NumberingFormat nf3;
nf3 = new NumberingFormat();
nf3.NumberFormatId = iExcelIndex++;
nf3.FormatCode = "\"\"#,##0.00;[Red]\"\"#,##0.00";
nfs.Append(nf3);
NumberingFormat nf4;
nf4 = new NumberingFormat();
nf4.NumberFormatId = iExcelIndex++;
nf4.FormatCode = "#";
nfs.Append(nf4);
nfs.Count = (uint)nfs.ChildElements.Count;
//************************** cell formats ***********************************
var cfs = stylesheet.CellFormats;//this should already contain a default StyleIndex of 0
var cf = new CellFormat();// Date time format is defined as StyleIndex = 1
cf.NumberFormatId = nf.NumberFormatId;
cf.FontId = 0;
cf.FillId = 0;
cf.BorderId = 0;
cf.FormatId = 1;
cf.ApplyNumberFormat = true;
cfs.Append(cf);
cf = new CellFormat();// Header format is defined as StyleINdex = 2
cf.NumberFormatId = nf.NumberFormatId;
cf.FontId = 0;
cf.FillId = 2;
cf.ApplyFill = true;
cf.BorderId = 0;
cf.FormatId = 0;
cf.ApplyNumberFormat = true;
cfs.Append(cf);
///**Style index = 3
CellFormat cellFormat1 = new CellFormat() { NumberFormatId = (UInt32Value)1,
FontId = (UInt32Value)0U,
FillId = (UInt32Value)0U,
BorderId = (UInt32Value)0U,
FormatId = (UInt32Value)0U,
ApplyNumberFormat = true };
cfs.Append(cellFormat1);
///**Style index = 4
CellFormat cellFormatdecimal = new CellFormat()
{
NumberFormatId = (UInt32Value)nf2.NumberFormatId,
FontId = (UInt32Value)0U,
FillId = (UInt32Value)0U,
BorderId = (UInt32Value)0U,
FormatId = (UInt32Value)0U,
ApplyNumberFormat = true
};
cfs.Append(cellFormatdecimal);
//Style index = 5
CellFormat cellFormat5 = new CellFormat()
{
NumberFormatId = (UInt32Value)nf3.NumberFormatId,
FontId = (UInt32Value)0U,
FillId = (UInt32Value)0U,
BorderId = (UInt32Value)0U,
FormatId = (UInt32Value)0U,
ApplyNumberFormat = true
};
cfs.Append(cellFormat5);
//Style index = 6
CellFormat cellFormat6 = new CellFormat()
{
NumberFormatId = (UInt32Value)nf4.NumberFormatId,
FontId = (UInt32Value)0U,
FillId = (UInt32Value)0U,
BorderId = (UInt32Value)0U,
FormatId = (UInt32Value)0U,
ApplyNumberFormat = true
};
cfs.Append(cellFormat6);
cfs.Count = (uint)cfs.ChildElements.Count;
var workbookStylesPart = workbookPart.AddNewPart<WorkbookStylesPart>();
var style = workbookStylesPart.Stylesheet = stylesheet;
style.Save();
}
And for the writecellvaluesax:
public void WriteCellValueSax(OpenXmlWriter writer, string cellValue, CellValues dataType, List<OpenXmlAttribute> attributes = null,int idFormat = 0,string columnname = "")
{
switch (dataType)
{
case CellValues.InlineString:
{
if (attributes == null)
{
attributes = new List<OpenXmlAttribute>();
}
attributes.Add(new OpenXmlAttribute("t", null, "inlineStr"));
writer.WriteStartElement(new Cell(), attributes);
writer.WriteElement(new InlineString(new Text(cellValue)));
writer.WriteEndElement();
break;
}
case CellValues.Number:
{
if (attributes == null)
{
attributes = new List<OpenXmlAttribute>();
}
writer.WriteStartElement(new Cell() {DataType = CellValues.Number,StyleIndex = FormatoCampo(columnname,cellValue.Length)});
writer.WriteElement(new CellValue(cellValue));
writer.WriteEndElement();
break;
}
case CellValues.SharedString:
{
if (attributes == null)
{
attributes = new List<OpenXmlAttribute>();
}
attributes.Add(new OpenXmlAttribute("t", null, "s"));//shared string type
writer.WriteStartElement(new Cell(), attributes);
if (!_shareStringDictionary.ContainsKey(cellValue))
{
_shareStringDictionary.Add(cellValue, _shareStringMaxIndex);
_shareStringMaxIndex++;
}
//writing the index as the cell value
writer.WriteElement(new CellValue(_shareStringDictionary[cellValue].ToString()));
writer.WriteEndElement();//cell
break;
}
case CellValues.Date:
{
if (attributes == null)
{
writer.WriteStartElement(new Cell() { DataType = CellValues.Number });
}
else
{
writer.WriteStartElement(new Cell() { DataType = CellValues.Number }, attributes);
}
writer.WriteElement(new CellValue(cellValue));
writer.WriteEndElement();
break;
}
case CellValues.Boolean:
{
if (attributes == null)
{
attributes = new List<OpenXmlAttribute>();
}
attributes.Add(new OpenXmlAttribute("t", null, "b"));//boolean type
writer.WriteStartElement(new Cell(), attributes);
writer.WriteElement(new CellValue(cellValue == "True" ? "1" : "0"));
writer.WriteEndElement();
break;
}
default:
{
if (attributes == null)
{
writer.WriteStartElement(new Cell() { DataType = dataType });
}
else
{
writer.WriteStartElement(new Cell() { DataType = dataType }, attributes);
}
writer.WriteElement(new CellValue(cellValue));
writer.WriteEndElement();
break;
}
}
}
I tried unziping the xlsx file to see if i could manually find anything weird, but nothing shows
I am just using OpenXML for manipulating docx document. I have templates that has notation like
{{userFirstName}}
{{tableOfUsers}}
{{signatureImage}} etc
I need to replace those text with table, image etc. How to do that in Openxml ?
I'm using C# .Net core 3.1 with OpenXML 2.5
My code was like this, but the table still not inserted into the right place:
var fileName = Path.Combine(_hostingEnv.WebRootPath, "test/test.docx");
var fileNameResult = Path.Combine(_hostingEnv.WebRootPath, "test/result.docx");
byte[] byteArray = System.IO.File.ReadAllBytes(fileName);
using (MemoryStream stream = new MemoryStream())
{
stream.Write(byteArray, 0, (int)byteArray.Length);
using (WordprocessingDocument wd = WordprocessingDocument.Open(stream, true))
{
Table table = new Table();
// Create a TableProperties object and specify its border information.
TableProperties tblProp = new TableProperties(
new TableBorders(
new TopBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.Dashed),
Size = 24
},
new BottomBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.Dashed),
Size = 24
},
new LeftBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.Dashed),
Size = 24
},
new RightBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.Dashed),
Size = 24
},
new InsideHorizontalBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.Dashed),
Size = 24
},
new InsideVerticalBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.Dashed),
Size = 24
}
)
);
// Append the TableProperties object to the empty table.
table.AppendChild<TableProperties>(tblProp);
// Create a row.
TableRow tr = new TableRow();
// Create a cell.
TableCell tc1 = new TableCell();
// Specify the width property of the table cell.
tc1.Append(new TableCellProperties(
new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2400" }));
// Specify the table cell content.
tc1.Append(new Paragraph(new Run(new Text("some text"))));
// Append the table cell to the table row.
tr.Append(tc1);
// Create a second table cell by copying the OuterXml value of the first table cell.
TableCell tc2 = new TableCell(tc1.OuterXml);
// Append the table cell to the table row.
tr.Append(tc2);
// Append the table row to the table.
table.Append(tr);
var tblStr = table.ToString();
//wd.MainDocumentPart.Document.Body.Append(table);
Text tablePl = wd.MainDocumentPart.Document.Body.Descendants<Text>().Where(x => x.Text == "{{tableOfUsers}}").First();
if(tablePl != null)
{
var parent = tablePl.Parent;
tablePl.Parent.InsertAfter<Table>(table, tablePl);
tablePl.Remove();
}
string docText = null;
using (StreamReader sr = new StreamReader(wd.MainDocumentPart.GetStream()))
{
docText = sr.ReadToEnd();
}
Regex regexText = new Regex("{{name}}");
docText = regexText.Replace(docText, "Claire " + DateTime.Now.ToString());
// Regex regextable = new Regex("{{tableOfUsers}}");
// docText = regextable.Replace(docText, tblStr);
using (StreamWriter sw = new StreamWriter(wd.MainDocumentPart.GetStream(FileMode.Create)))
{
sw.Write(docText);
}
}
await System.IO.File.WriteAllBytesAsync(fileNameResult, stream.ToArray());
}
_fileRepo.SetPath("test");
string fileName2 = "result.docx";
var data = await _fileRepo.DownloadFile(fileName2);
return File(data, "application/octet-stram", "filename.docx");
}
My docx file looks like
Hello {{name}}
Here is the list of users : {{tableOfUsers}}
Sincerely,
{{signatureImage}}
Use the code below to insert a table:
............
string tablePlaceholder = "{{tableOfUsers}}";
Text tablePl = wd.MainDocumentPart.Document.Body
.Descendants<Text>()
.Where(x => x.Text.Contains(tablePlaceholder))
.First();
if (tablePl != null)
{
//Insert the table after the paragraph.
var parent = tablePl.Parent.Parent.Parent;
parent.InsertAfter(table, tablePl.Parent.Parent);
tablePl.Text = tablePl.Text.Replace(tablePlaceholder, "");
wd.MainDocumentPart.Document.Save();
}
string docText = wd.MainDocumentPart.Document.Body.OuterXml;
Regex regexText = new Regex("{{name}}");
docText = regexText.Replace(docText, "Claire " + DateTime.Now.ToString());
wd.MainDocumentPart.Document.Body = new Body(docText);
wd.MainDocumentPart.Document.Save();
.............
You are looking for {{table}} in your code, but the notation in your template is {{tableOfUsers}}.
I'm trying to format an Excel sheet. The header should have bold font and orange background. When I open the sheet, Excel gives me an error saying the document is invalid, and it open with all cells bold and no background in the header.
This is how a set the style.
.....
workbookStylePart = workbookpart.AddNewPart<WorkbookStylesPart>();
workbookStylePart.Stylesheet = CreateStylesheet();
workbookStylePart.Stylesheet.Save();
.....
cell.StyleIndex = 0U; // I suppose the style index is 0
This the style definition:
private static Stylesheet CreateStylesheet()
{
Stylesheet stylesheet = new Stylesheet() { MCAttributes = new MarkupCompatibilityAttributes() { Ignorable = "x14ac" } };
stylesheet.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
stylesheet.AddNamespaceDeclaration("x14ac", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac");
Fonts fonts = new Fonts() { Count = 1U, KnownFonts = true };
Font boldFont = new Font();
Bold bold = new Bold();
boldFont.Append(bold);
fonts.Append(boldFont);
Fills fills = new Fills() { Count = 1U };
// FillId = 0, orange
Fill orangeFill = new Fill();
PatternFill orangePatternFill = new PatternFill() { PatternType = PatternValues.Solid };
BackgroundColor orangeColor = new BackgroundColor() { Rgb = "FFA500" };
orangePatternFill.Append(orangeColor);
orangeFill.Append(orangePatternFill);
fills.Append(orangeFill);
CellFormats cellFormats = new CellFormats() { Count = 1U };
CellFormat headerBoldOrangeBgFormat = new CellFormat() { FontId = 0U, FillId = 0U , ApplyFill = true};
cellFormats.Append(headerBoldOrangeBgFormat);
stylesheet.Append(fonts);
stylesheet.Append(fills);
stylesheet.Append(cellFormats);
return stylesheet;
}
The ClosedXML library is a high-level wrapper over OpenXML. I recommend that you use ClosedXML. In addition, there is a ClosedXML.Report library that generates an Excel file based on the XLSX-template.
https://github.com/ClosedXML/ClosedXML
https://github.com/ClosedXML/ClosedXML.Report
I have written a method to insert a table in a word document using Open XML. The method accepts a generic list and a few parameters to control number of columns, column headings etc.
That all works fine.
However when populating the cells in the table I want to pull out the values for each row and place them in their corresponding columns. Given the names of the properties are going to change depending on the contents of the generic list, I am not sure how to accomplish this.
Anyone that can point me in the right direction it would be appreciated.
void InsertTable<T>(List<T> tableData, int[] tableHeadingCount, string[] columnHeadings, string locationInDocument)
{
using (WordprocessingDocument myDoc = WordprocessingDocument.Open(_newDocument, true))
{
var docPart = myDoc.MainDocumentPart;
var doc = docPart.Document;
var table = new Table();
var tableBorderTop = new TopBorder();
var tableBorderBottom = new BottomBorder();
var tableBorderLeft = new LeftBorder();
var tableBorderRight = new RightBorder();
var tableBorderHorizontal = new InsideHorizontalBorder();
var tableBorderVertical = new InsideVerticalBorder();
var tableProperties = new TableProperties();
var borders = new TableBorders();
// Set Border Styles for Table
tableBorderTop.Val = BorderValues.Single;
tableBorderTop.Size = 6;
tableBorderBottom.Val = BorderValues.Single;
tableBorderBottom.Size = 6;
tableBorderLeft.Val = BorderValues.Single;
tableBorderLeft.Size = 6;
tableBorderRight.Val = BorderValues.Single;
tableBorderRight.Size = 6;
tableBorderHorizontal.Val = BorderValues.Single;
tableBorderHorizontal.Size = 6;
tableBorderVertical.Val = BorderValues.Single;
tableBorderVertical.Size = 6;
// Assign Border Styles to Table Borders
borders.TopBorder = tableBorderTop;
borders.BottomBorder = tableBorderBottom;
borders.LeftBorder = tableBorderLeft;
borders.RightBorder = tableBorderRight;
borders.InsideHorizontalBorder = tableBorderHorizontal;
borders.InsideVerticalBorder = tableBorderVertical;
// Append Border Styles to Table Properties
tableProperties.Append(borders);
// Assign Table Properties to Table
table.Append(tableProperties);
var tableRowHeader = new TableRow();
tableRowHeader.Append(new TableRowHeight() { Val = 2000 });
for (int i = 0; i < tableHeadingCount.Length; i++)
{
var tableCellHeader = new TableCell();
//Assign Font Properties to Run
var runPropHeader = new RunProperties();
runPropHeader.Append(new Bold());
runPropHeader.Append(new Color() { Val = "000000" });
//Create New Run
var runHeader = new Run();
//Assign Font Properties to Run
runHeader.Append(runPropHeader);
var columnHeader = new Text();
//Assign the Pay Rule Name to the Run
columnHeader = new Text(columnHeadings[i]);
runHeader.Append(columnHeader);
//Create Properties for Paragraph
var justificationHeader = new Justification();
justificationHeader.Val = JustificationValues.Left;
var paraPropsHeader = new ParagraphProperties(justificationHeader);
SpacingBetweenLines spacing = new SpacingBetweenLines() { Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0" };
paraPropsHeader.Append(spacing);
var paragraphHeader = new Paragraph();
paragraphHeader.Append(paraPropsHeader);
paragraphHeader.Append(runHeader);
tableCellHeader.Append(paragraphHeader);
var tableCellPropertiesHeader = new TableCellProperties();
var tableCellWidthHeader = new TableCellWidth();
tableCellPropertiesHeader.Append(new Shading() { Val = ShadingPatternValues.Clear, Color = "auto", Fill = "#C0C0C0" });
var textDirectionHeader = new TextDirection();
textDirectionHeader.Val = TextDirectionValues.BottomToTopLeftToRight;
tableCellPropertiesHeader.Append(textDirectionHeader);
tableCellWidthHeader.Type = TableWidthUnitValues.Dxa;
tableCellWidthHeader.Width = "2000";
tableCellPropertiesHeader.Append(tableCellWidthHeader);
tableCellHeader.Append(tableCellPropertiesHeader);
tableRowHeader.Append(tableCellHeader);
}
tableRowHeader.AppendChild(new TableHeader());
table.Append(tableRowHeader);
//Create New Row in Table for Each Record
foreach (var record in tableData)
{
var tableRow = new TableRow();
for (int i = 0; i < tableHeadingCount.Length; i++)
{
//**** This is where I dynamically want to iterate through selected properties and output the value ****
var propertyText = "Test";
var tableCell = new TableCell();
//Assign Font Properties to Run
var runProp = new RunProperties();
runProp.Append(new Bold());
runProp.Append(new Color() { Val = "000000" });
//Create New Run
var run = new Run();
//Assign Font Properties to Run
run.Append(runProp);
//Assign the text to the Run
var text = new Text(propertyText);
run.Append(text);
//Create Properties for Paragraph
var justification = new Justification();
justification.Val = JustificationValues.Left;
var paraProps = new ParagraphProperties(justification);
var paragraph = new Paragraph();
paragraph.Append(paraProps);
paragraph.Append(run);
tableCell.Append(paragraph);
var tableCellProperties = new TableCellProperties();
var tableCellWidth = new TableCellWidth();
tableCellWidth.Type = TableWidthUnitValues.Dxa;
tableCellWidth.Width = "2000";
tableCellProperties.Append(tableCellWidth);
tableCell.Append(tableCellProperties);
tableRow.Append(tableCell);
}
table.Append(tableRow);
}
var res = from bm in docPart.Document.Body.Descendants<BookmarkStart>()
where bm.Name == locationInDocument
select bm;
var bookmark = res.SingleOrDefault();
var parent = bookmark.Parent; // bookmark's parent element
Paragraph newParagraph = new Paragraph();
parent.InsertAfterSelf(newParagraph);
if (bookmark != null)
{
newParagraph.InsertBeforeSelf(table);
}
}
}
I resolved this issue by tackling the problem another way. Essentially rather than passing a List to the Insert Table Method. I decided to Pass a Multi-Dimensional Array with all the data need for the table including the table headings. This essentially meant that the Insert Table method would be more generic and any customization i.e. Generating Data, Specifying Column Headings etc would be done in the Method calling Insert Table.
How can I change the font family of the document via OpenXml ?
I tried some ways but, when I open the document, it's always in Calibri
Follow my code, and what I tried.
The Header Builder I think is useless to post
private static void BuildDocument(string fileName, List<string> lista, string tipo)
{
using (var w = WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document))
{
var mp = w.AddMainDocumentPart();
var d = new DocumentFormat.OpenXml.Wordprocessing.Document();
var b = new Body();
var p = new DocumentFormat.OpenXml.Wordprocessing.Paragraph();
var r = new Run();
// Get and format the text.
for (int i = 0; i < lista.Count; i++)
{
Text t = new Text();
t.Text = lista[i];
if (t.Text == " ")
{
r.Append(new CarriageReturn());
}
else
{
r.Append(t);
r.Append(new CarriageReturn());
}
}
// What I tried
var rPr = new RunProperties(new RunFonts() { Ascii = "Arial" });
lista.Clear();
p.Append(r);
b.Append(p);
var hp = mp.AddNewPart<HeaderPart>();
string headerRelationshipID = mp.GetIdOfPart(hp);
var sectPr = new SectionProperties();
var headerReference = new HeaderReference();
headerReference.Id = headerRelationshipID;
headerReference.Type = HeaderFooterValues.Default;
sectPr.Append(headerReference);
b.Append(sectPr);
d.Append(b);
// Customize the header.
if (tipo == "alugar")
{
hp.Header = BuildHeader(hp, "Anúncio Aluguel de Imóvel");
}
else if (tipo == "vender")
{
hp.Header = BuildHeader(hp, "Anúncio Venda de Imóvel");
}
else
{
hp.Header = BuildHeader(hp, "Aluguel/Venda de Imóvel");
}
hp.Header.Save();
mp.Document = d;
mp.Document.Save();
w.Close();
}
}
In order to style your text with a specific font follow the steps listed below:
Create an instance of the RunProperties class.
Create an instance of the RunFont class. Set the Ascii property to the desired font familiy.
Specify the size of your font (half-point font size) using the FontSize class.
Prepend the RunProperties instance to your run containing the text to style.
Here is a small code example illustrating the steps described above:
private static void BuildDocument(string fileName, List<string> text)
{
using (var wordDoc = WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document))
{
var mainPart = wordDoc.AddMainDocumentPart();
mainPart.Document = new Document();
var run = new Run();
foreach (string currText in text)
{
run.AppendChild(new Text(currText));
run.AppendChild(new CarriageReturn());
}
var paragraph = new Paragraph(run);
var body = new Body(paragraph);
mainPart.Document.Append(body);
var runProp = new RunProperties();
var runFont = new RunFonts { Ascii = "Arial" };
// 48 half-point font size
var size = new FontSize { Val = new StringValue("48") };
runProp.Append(runFont);
runProp.Append(size);
run.PrependChild(runProp);
mainPart.Document.Save();
wordDoc.Close();
}
}
Hope, this helps.
If you are using Stylesheet just add an instance of FontName property at appropriate font index during Fonts initilaization.
private Stylesheet GenerateStylesheet()
{
Stylesheet styleSheet = null;
Fonts fonts = new Fonts(
new Font( // Index 0 - default
new FontSize() { Val = 8 },
new FontName() { Val = "Arial"} //i.e. or any other font name as string
);
Fills fills = new Fills( new Fill(new PatternFill() { PatternType = PatternValues.None }));
Borders borders = new Borders( new Border() );
CellFormats cellFormats = new CellFormats( new CellFormat () );
styleSheet = new Stylesheet(fonts, fills, borders, cellFormats);
return styleSheet;
}
Then use it in Workbook style part as below.
WorkbookStylesPart stylePart = workbookPart.AddNewPart<WorkbookStylesPart>();
stylePart.Stylesheet = GenerateStylesheet();
stylePart.Stylesheet.Save();