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
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 creating a table in OpenXml with C# in a Word file. I used some code mentioned in this question to set the fontsize of the text in the cells. It works fine for the cells that contain text, but the empty cells seem to be given the normal style, and with that a bigger font size, which makes the row height bigger.
Here is my sample code with a single row with a single cell, where the font size should be 9:
TableRow tr = new TableRow();
TableCell tc = new TableCell();
Paragraph par = new Paragraph();
Run run = new Run();
Text txt = new Text("txt");
RunProperties runProps = new RunProperties();
FontSize fontSize = new Fontsize() { Val = "18" }; // font size 9
runProps.Append(fontSize);
run.Append(runProps);
run.Append(txt);
para.Append(run);
tc.Append(para);
tr.Append(tc);
Here is an example of the resulting table. As you can see the middle row is taller than the others. In the cells that say "txt" the font size is 9, but in the blank cell the font size is 11. The code above is used for all the cells, where the empty cell simply has the text "". When I looked at the file with the Open XML Tool, I can see that the RunProperties with value 18 is there for all the cells including the empty one.
How do I set the font size of a cell without displaying any text?
I confirm what you report. One way around it would be to substitute a space " " for the "empty" string, adding "space preserve" to the text run, of course.
Another possibility would be to create a character style and apply it to the table cells. This turned out to be trickier than it sounds as the style needs to be applied twice to cells that contain text: once to the ParagraphMarkRunProperties and once to the RunProperties. For empty cells the style need be applied only to the ParagraphMarkRunProperties.
Actually, on reflection, you can use the same approach for the font size...
I've included both approaches in the code below. The one for just the font size is commented out (four lines).
The sample code assumes that the third cell of the one-row, four column table, has no content. Run and Text information is added only when there is content.
private void btnCreateTable_Click(object sender, EventArgs e)
{
string filePath = #"C:\X\TestCreateTAble.docx";
using (WordprocessingDocument pkg = WordprocessingDocument.Open(filePath, true))
{
MainDocumentPart partDoc = pkg.MainDocumentPart;
Document doc = partDoc.Document;
StyleDefinitionsPart stylDefPart = partDoc.StyleDefinitionsPart;
Styles styls = stylDefPart.Styles;
Style styl = CreateTableCharacterStyle();
stylDefPart.Styles.AppendChild(styl);
Table t = new Table();
TableRow tr = new TableRow();
for (int i = 1; i <= 4; i++)
{
TableCell tc = new TableCell(new TableCellProperties(new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "500" }));
Paragraph para = new Paragraph();
ParagraphProperties paraProps = new ParagraphProperties();
ParagraphMarkRunProperties paraRunProps = new ParagraphMarkRunProperties();
RunStyle runStyl = new RunStyle() { Val = "Table9Point" };
paraRunProps.Append(runStyl);
// FontSize runFont = new FontSize() {Val = "18" };
// paraRunProps.Append(runFont);
paraProps.Append(paraRunProps);
para.Append(paraProps);
Run run = new Run();
Text txt = null;
if (i == 3)
{
}
else
{
txt = new Text("txt");
txt.Space = SpaceProcessingModeValues.Preserve;
RunProperties runProps = new RunProperties();
RunStyle inRunStyl = (RunStyle) runStyl.Clone();
runProps.Append(inRunStyl);
// FontSize inRunFont = (FontSize) runFont.Clone();
// runProps.Append(inRunFont);
run.Append(runProps);
run.Append(txt);
para.Append(run);
}
tc.Append(para);
tr.Append(tc);
}
t.Append(tr);
//Insert at end of document
SectionProperties sectProps = doc.Body.Elements<SectionProperties>().LastOrDefault();
doc.Body.InsertBefore(t, sectProps);
}
}
private Style CreateTableCharacterStyle()
{
Style styl = new Style()
{
CustomStyle = true,
StyleId = "Table9Point",
Type = StyleValues.Character,
};
StyleName stylName = new StyleName() { Val = "Table9Point" };
styl.AppendChild(stylName);
StyleRunProperties stylRunProps = new StyleRunProperties();
stylRunProps.FontSize = new FontSize() { Val = "18" };
styl.AppendChild(stylRunProps);
BasedOn basedOn1 = new BasedOn() { Val = "DefaultParagraphFont" };
styl.AppendChild(basedOn1);
return styl;
}
Just need to set the FontSize and FontSizeComplexScript for the ParagraphProperties and RunProperties, like this:
var cell = new TableCell(
new Paragraph(
new ParagraphProperties(
new SpacingBetweenLines { LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0" },
new RunProperties(
new FontSize { Val = "18" },
new FontSizeComplexScript { Val = "18" })),
new Run(
new RunProperties(
new FontSize { Val = "18" },
new FontSizeComplexScript { Val = "18" }),
new Text { Text = String.Empty, Space = SpaceProcessingModeValues.Preserve })));
I am using a dll to create methods that generates me the logic to create a paragraph based on the parameters that are passed:
for example on my C# code i have this:
// document permission title
DocRun accessTypeTitle = new DocRun();
Run permissionTitle = accessTypeTitle.createParagraph("DOCUMENT ACCESS", PARAGRAPHCOLOR,FONTSIZETEXT,DEFAULTFONT);
i have my method on my dll that does the logic:
public class DocRun
{
public Run createParagraph(String text, String colorVal, String fontSize,String font)
{
Run run = new Run() { RsidRunProperties = "00C53974" };
RunProperties runProperties = new RunProperties();
RunFonts runFonts = new RunFonts() { Ascii = font, HighAnsi = font, EastAsia = "Segoe UI", ComplexScript = font };
Color color = new Color() { Val = colorVal };
//Kern kern = new Kern() { Val = (UInt32Value)24U };
FontSize fontSize11 = new FontSize() { Val = fontSize };
FontSizeComplexScript fontSizeComplexScript11 = new FontSizeComplexScript() { Val = fontSize };
runProperties.Append(runFonts);
runProperties.Append(color);
//runProperties.Append(kern);
runProperties.Append(fontSize11);
runProperties.Append(fontSizeComplexScript11);
Text t = new Text(text)
{
Text = text,
Space = SpaceProcessingModeValues.Preserve
};
run.Append(runProperties);
run.Append(t);
return run;
}
}
}
after i return the run, i can do the same with the images nd other paragraph and just append them to the doc like this:
var stream = new MemoryStream();
using (WordprocessingDocument doc = WordprocessingDocument.Create(stream, WordprocessingDocumentType.Document, true))
{
MainDocumentPart mainPart = doc.AddMainDocumentPart();
// Logo company construction
DocImage companyLogo = new DocImage();
Run imageLogo = companyLogo.imageCreator(mainPart,COMPANYLOGOPATH,COMPANYIMAGENAME,COMPANYLOGOWIDTH,COMPANYLOGOHEIGHT,COMPANYIMAGEALING);
DocImage titleShape = new DocImage();
Run imageShape = titleShape.imageCreator(mainPart, SHAPEIMAGEPATH, TITLESHAPEIMAGENAME, TITLESHAPEWIDTH, TITLESHAPEHEIGHT,SHAPEIMAGEALING);
DocImage clientImage = new DocImage();
Run clientLogo = titleShape.imageCreatorUrl(mainPart, SHAPEIMAGEPATH, TITLESHAPEIMAGENAME, TITLESHAPEWIDTHCLIENTLOGO, TITLESHAPEHEIGHTCLIENTLOGO, CLIENTIMAGEALIGN,clientLogoPath);
new Document(new Body()).Save(mainPart);
Body body = mainPart.Document.Body;
body.Append(new Paragraph(
new Run(imageLogo)));
body.Append(new Paragraph(
new Run(imageShape)));
body.Append(new Paragraph(
new Run(projectNameTxt)));
body.Append(new Paragraph(
new Run(clientLogo)));
body.Append(new Paragraph(
new Run(dateTxt)));
body.Append(new Paragraph(
new Run(permissionTitle)));
body.Append(new Paragraph(
new Run(permission)));
body.Append(new Paragraph(
new Run(disclaimerTitleTxt)));
body.Append(new Paragraph(
new Run(disclaimerDescriptionTxt)));
mainPart.Document.Save();
}
stream.Seek(0, SeekOrigin.Begin);
Directory.CreateDirectory(HostingEnvironment.MapPath(DOCUMENTSLOCATION));
System.IO.File.WriteAllBytes(HostingEnvironment.MapPath("~/Files/test5.docx"), stream.ToArray());
}
my problem is that the document generated font size are always half of the real size i defined on the openXML dll that i created.
I debuged the fontSize that i pass as the parameter and the fontsize received on the dll is the correct one, what is going on?
Thanks guys,
The FontSize is specified with a value which measures in half-points. So if you need a 11 point font, you need to specify the value to be 22.
This is also documented on page 13 in the e-book "Open XML Explained" by Wouter Van Vugt.
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;
}
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();