Format Font Inside Table OpenXML C# - c#

I want to make table using OpenXML WordProcessing. I want to format the font inside the cell. This is my code
MainDocumentPart mainDocumentPart = doc.AddMainDocumentPart();
mainDocumentPart.Document = new Document();
Body body = mainDocumentPart.Document.AppendChild(new Body());
RunProperties runHeader = new RunProperties();
RunFonts runFont = new RunFonts();
runFont.Ascii = "Lucida Sans";
runHeader.Append(runFont);
runHeader.Append(new Bold());
runHeader.Append(new FontSize() { Val = "16" });
//// Create a new table
Table tbl = new Table();
tr = new TableRow();
tc = new TableCell();
Paragraph paraHeader = new Paragraph();
Text heading_text = new Text("Company Name");
runHeader.Append(heading_text);
paraHeader.Append(runHeader);
tc.Append(paraHeader);
tr.Append(tc);
tbl.Append(tr);
body.AppendChild(tbl);
But when I open up on Microsoft Word, I got error. Its said that the file has problem with the contents

You are appending your text to your Run Properties, it needs to be appended to a Run.
try:
Text heading_text = new Text("Company Name");
////create the run
Run runHeaderRun = new Run();
////append the run properties and text to the run
runHeaderRun.Append(runHeader);
runHeaderRun.Append(heading_text);
////append the run to the paragraph
paraHeader.Append(runHeaderRun);
tc.Append(paraHeader);

RunProperties rp = new RunProperties();
RunFonts runFont = new RunFonts() { Ascii = "Calibri Light" };
rp.Append(runFont);
rp.Append(new Color() { Val = "#2E74B5" });
body.Append(new DocumentFormat.OpenXml.Wordprocessing.Paragraph(new Run(rp, new Text("3. Risk Assessment"))));
It's a really simple to use, try this.

Related

Set Multiple styles in a single excel cell using OfficeOpenXml in C#

I cannot find a way to style a single excel cell in different styles.
For example I need to make only some part of the string bold and leave the rest unbold in one cell.
I can only access Cells not characters in OpenXml.
Usually what I do to style the cell is,
ExcelPackage package = new ExcelPackage();
ExcelWorksheet ws = package.Workbook.Worksheets.Add("SheetName");
ws.Cells[1, 1].Style.Font.Bold = true;
I can't find a way to access characters in a cell. I saw some other excel plugins do the same but Is there any way OpenXml can do this? Any suggestions will be great. Thanks
The answer here works well.
You have to add the cell content as separate ExcelRichText objects.
Example:
ExcelRichText rt1 = ws.Cells[1, 1].RichText.Add("AB");
rt1.Bold = true; // bold just the "AB"
ExcelRichText rt2 = ws.Cells[1, 1].RichText.Add("CD");
Output will be: "ABCD"
Note: You will need to reference the namespace OfficeOpenXml.Style
This is how you can add partial styles in an excel sheet using OpenXML.
//Partial Cell Styling
uint currentRow = 2;
Row newRow = new Row() { RowIndex = currentRow };
//create a new inline string cell
Cell cell = new Cell() { CellReference = "J" + currentRow.ToString() };
cell.DataType = CellValues.InlineString;
//create a run for the bold text
Run run1 = new Run();
run1.Append(new Text("By: "));
//create a second run for the non-bod text
Run run2 = new Run();
run2.Append(new Text(Environment.NewLine + " SAHIL VIG") { Space = SpaceProcessingModeValues.Preserve });
//create runproperties and append a "Bold" to them
RunProperties run2Properties = new RunProperties();
run2Properties.Append(new Bold());
//set the first runs RunProperties to the RunProperties containing the bold
run2.RunProperties = run2Properties;
//create a new inline string and append both runs
InlineString inlineString = new InlineString();
inlineString.Append(run1);
inlineString.Append(run2);
//append the inlineString to the cell.
cell.Append(inlineString);
//append the cell to the row
newRow.Append(cell);
sheetData.Append(newRow);

openxml use predefined styles in a blank word

I want to apply some styles that are predefined in word. My code is as follows, but the style "Heading1" doesn't work.
WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(document, true);
Body body = wordprocessingDocument.MainDocumentPart.Document.Body;
Paragraph p = new Paragraph();
ParagraphProperties ppr = new ParagraphProperties();
ParagraphStyleId stid = new ParagraphStyleId() { Val = "Heading1" };
ppr.Append(stid);
p.Append(ppr);

aspose word add style doesn't work

I add a style in doc but if style font Name is Mounted on word It does not work!!!
my font is a PersianFont
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Aspose.Words.Style style = doc.Styles.Add(StyleType.Paragraph, "newStyle");
style.IsQuickStyle = true;
style.Font.Size = 24;
style.Font.Name = "B Mitra";
builder.ParagraphFormat.Style = style;
builder.Writeln("سلام");
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Aspose.Words.Style style = doc.Styles.Add(StyleType.Paragraph, "newStyle");
style.IsQuickStyle = true;
style.Font.Size = 24;
style.Font.SizeBi= 24;
style.Font.Name = "B Mitra";
style.Font.NameBi= "B Mitra";
builder.ParagraphFormat.Style = style;
builder.Writeln("سلام");

File format error after open downloaded excel file

In my app, I am trying to download excel file from byte array content in mvc. After file downloaded, when I open that downloaded file I am getting error.
"The file you're trying to open 'XXXX.xls' is in a different format
than specified by the file extension. Verify that the file is not
corrupted and is from a trusted source before opening the file. Do you
want to open the file now?"
after click on yes in above error I am getting another error
Excel found unreadable content in 'XXXX.xls'. Do you want to
recover the contents of this workbook? If you trust the source of this
workbook, click Yes.
Again when I am click on yes in above error message I am getting first error message again.
"The file you're trying to open 'XXXX.xls' is in a different format
than specified by the file extension. Verify that the file is not
corrupted and is from a trusted source before opening the file. Do you
want to open the file now?"
After click on yes in above error message, excel opens a repair popup showing message inside it. The message is
Repaired Records: Format from /xl/styles.xml part (Styles)
Here is my controller code
[HttpPost, FileDownload]
public FileContentResult GetReport(DateTime StartDate, DateTime EndDate, int ReportType)
{
var reportData = new Model().GetReport(StartDate, EndDate, ReportType);
string fileName = "Report " + (TimeZoneUtil.ConvertUtcDateTimeToESTDateTime(DateTime.UtcNow).ToString("yyyy:MM:dd:hh:mm:ss")) + ".xls";
return File(reportData, MimeMapping.GetMimeMapping(fileName), fileName);
}
I am calling this method in view using jQuery File Download Plugin and my code is
var dataToSend = { "StartDate": $("#dtpreportstartdate").val(), "EndDate": $("#dtpreportenddate").val(), "ReportType": value };
$.fileDownload(GetBaseUrl() + "Dashboard/GetReport",
{
preparingMessageHtml: "success message",
failMessageHtml: "Error message",
httpMethod: "POST",
data: dataToSend
});
Below is my method to get excel content
public byte[] CreateReportFile(List<BGClass> BGRows)
{
MemoryStream ms = new MemoryStream();
SpreadsheetDocument xl = SpreadsheetDocument.Create(ms, SpreadsheetDocumentType.Workbook);
WorkbookPart wbp = xl.AddWorkbookPart();
WorksheetPart wsp = wbp.AddNewPart<WorksheetPart>();
Workbook wb = new Workbook();
FileVersion fv = new FileVersion();
fv.ApplicationName = "Microsoft Office Excel";
Worksheet ws = new Worksheet();
SheetData sd = new SheetData();
AddStyleSheet(ref xl);
Row headerRow = new Row();
Cell CreatedDateHeaderCell = new Cell() { StyleIndex = Convert.ToUInt32(1) };
CreatedDateHeaderCell.DataType = CellValues.String;
CreatedDateHeaderCell.CellValue = new CellValue("Created Date");
headerRow.Append(CreatedDateHeaderCell);
Cell BackgroundNameHeaderCell = new Cell() { StyleIndex = Convert.ToUInt32(1) };
BackgroundNameHeaderCell.DataType = CellValues.String;
BackgroundNameHeaderCell.CellValue = new CellValue("Bg Name");
headerRow.Append(BackgroundNameHeaderCell);
sd.Append(headerRow);
foreach (BGClass reportRow in BGRows)
{
Row dataRow = new Row();
Cell CreatedDateDataCell = new Cell();
CreatedDateDataCell.DataType = CellValues.String;
CreatedDateDataCell.CellValue = new CellValue(TimeZoneHelper.ConvertUtcDateTimeToESTDateTime(reportRow.CreatedDate).ToString());
dataRow.Append(CreatedDateDataCell);
Cell BackgroundNameDataCell = new Cell();
BackgroundNameDataCell.DataType = CellValues.String;
BackgroundNameDataCell.CellValue = new CellValue(reportRow.BackgroundName);
dataRow.Append(BackgroundNameDataCell);
}
ws.Append(sd);
wsp.Worksheet = ws;
wsp.Worksheet.Save();
Sheets sheets = new Sheets();
Sheet sheet = new Sheet();
sheet.Name = "Report";
sheet.SheetId = 1;
sheet.Id = wbp.GetIdOfPart(wsp);
sheets.Append(sheet);
wb.Append(fv);
wb.Append(sheets);
xl.WorkbookPart.Workbook = wb;
xl.WorkbookPart.Workbook.Save();
xl.Close();
return ms.ToArray();
}
What is wrong with the code? Why I am getting excel error while opening a file?
I tried lots of blog to change MIME type, but nothing work for me.
Any idea?
You're using SpreadsheetDocument.Create()from the OpenXML SDK.
This indicates that you're writing an XLSX file, yet you serve the file with an XLS extension and according MIME type.
Change the file extension to .xlsx, indicating the XML format.
Can I suggest something ?
Why not use a free C# library, like mine (link below), which you can pass your List<> variable to, and it'll create a perfectly working .xlsx file for you.
CodeProject: Export to Excel, in C#
One line of code, and this problem goes away:
public void CreateReportFile(List<BGClass> BGRows)
{
CreateExcelFile.CreateExcelDocument(BGRows, "SomeFilename.xlsx");
}
All C# source code is provided free of charge.
I solved the problem after did some research. I am applying style to header row in excel using function AddStyleSheet(ref xl);. Problem occurs in that method I missing few parameters while applying style to cell.
My old method is
private WorkbookStylesPart AddStyleSheet(ref SpreadsheetDocument spreadsheet)
{
WorkbookStylesPart stylesheet = spreadsheet.WorkbookPart.AddNewPart<WorkbookStylesPart>();
Stylesheet workbookstylesheet = new Stylesheet();
Font fontBold = new Font(new FontName() { Val = "Arial" }); // Default font
Font defaultFont = new Font(new FontName() { Val = "Arial" }); // Bold font
Bold bold = new Bold();
defaultFont.Append(bold);
Fonts fonts = new Fonts(); // <APENDING Fonts>
fonts.Append(fontBold);
fonts.Append(defaultFont);
//// <Fills>
//Fill fill0 = new Fill(); // Default fill
//Fills fills = new Fills(); // <APENDING Fills>
//fills.Append(fill0);
// <Borders>
//Border border0 = new Border(); // Defualt border
//Borders borders = new Borders(); // <APENDING Borders>
//borders.Append(border0);
// <CellFormats>
CellFormat cellformat0 = new CellFormat() { FontId = 0, FillId = 0, BorderId = 0 }; // Default style : Mandatory | Style ID =0
CellFormat cellformat1 = new CellFormat() { FontId = 1 }; // Style with Bold text ; Style ID = 1
// <APENDING CellFormats>
CellFormats cellformats = new CellFormats();
cellformats.Append(cellformat0);
cellformats.Append(cellformat1);
// Append FONTS, FILLS , BORDERS & CellFormats to stylesheet <Preserve the ORDER>
workbookstylesheet.Append(fonts);
//workbookstylesheet.Append(fills);
//workbookstylesheet.Append(borders);
workbookstylesheet.Append(cellformats);
// Finalize
stylesheet.Stylesheet = workbookstylesheet;
stylesheet.Stylesheet.Save();
return stylesheet;
}
Here in this function I commented Fill and border section as I don't need it. But if you don't use it while applying style index it will give you "unreachable content" error, which I was facing.
So I changed my method and add Fill and border section to style. Here is my updated method.
private WorkbookStylesPart AddStyleSheet(ref SpreadsheetDocument spreadsheet)
{
WorkbookStylesPart stylesheet = spreadsheet.WorkbookPart.AddNewPart<WorkbookStylesPart>();
Stylesheet workbookstylesheet = new Stylesheet(
new Fonts(
new Font( // Index 0 – The default font.
new FontSize() { Val = 11 },
new Color() { Rgb = new HexBinaryValue() { Value = "000000" } },
new FontName() { Val = "Arial" }),
new Font( // Index 1 – The bold font.
new Bold(),
new FontSize() { Val = 11 },
new Color() { Rgb = new HexBinaryValue() { Value = "000000" } },
new FontName() { Val = "Arial" })
),
new Fills(
new Fill( // Index 0 – The default fill.
new PatternFill() { PatternType = PatternValues.None })
),
new Borders(
new Border( // Index 0 – The default border.
new LeftBorder(),
new RightBorder(),
new TopBorder(),
new BottomBorder(),
new DiagonalBorder())
),
new CellFormats(
new CellFormat() { FontId = 0, FillId = 0, BorderId = 0 }, // Index 0 – The default cell style. If a cell does not have a style index applied it will use this style combination instead
new CellFormat() { FontId = 1, FillId = 0, BorderId = 0 } // Index 1 – Bold
)
);
stylesheet.Stylesheet = workbookstylesheet;
stylesheet.Stylesheet.Save();
return stylesheet;
}
For ref link
https://blogs.msdn.microsoft.com/chrisquon/2009/11/30/stylizing-your-excel-worksheets-with-open-xml-2-0/.

How to make excel work sheet header row bold using OpenXML

I am using openXML, Asp.net and c# to create an Excel workbook, I have a requirement that to make Header row of all sheets should be bold.
WorkbookStylesPart stylesPart = workbookpart.AddNewPart<WorkbookStylesPart>();
stylesPart.Stylesheet = CreateStylesheet();
stylesPart.Stylesheet.Save();
}
private static Stylesheet CreateStylesheet()
{
Stylesheet ss = new Stylesheet();
Fonts fts = new Fonts();
DocumentFormat.OpenXml.Spreadsheet.Font ft = new DocumentFormat.OpenXml.Spreadsheet.Font();
Bold fbld = new Bold();
FontName ftn = new FontName();
ftn.Val = "Calibri";
DocumentFormat.OpenXml.Spreadsheet.FontSize ftsz = new DocumentFormat.OpenXml.Spreadsheet.FontSize();
ftsz.Val = 11;
ft.FontName = ftn;
ft.FontSize = ftsz;
ft.Bold = fbld;
fts.Append(ft);
fts.Count = (uint)fts.ChildElements.Count;
ss.Append(fts);
return ss;
}
It is making all the cells bold, I am missing the code that apply this to a particular row/cells
Thanks in Advance,
AR
I got the Answer from another post.
Create Excel file with style tag using OpenXmlWriter SAX
private static Stylesheet CreateStylesheet()
{
Stylesheet ss = new Stylesheet();
Font font0 = new Font(); // Default font
Font font1 = new Font(); // Bold font
Bold bold = new Bold();
font1.Append(bold);
Fonts fonts = new Fonts(); // <APENDING Fonts>
fonts.Append(font0);
fonts.Append(font1);
// <Fills>
Fill fill0 = new Fill(); // Default fill
Fills fills = new Fills(); // <APENDING Fills>
fills.Append(fill0);
// <Borders>
Border border0 = new Border(); // Defualt border
Borders borders = new Borders(); // <APENDING Borders>
borders.Append(border0);
CellFormat cellformat0 = new CellFormat() { FontId = 0, FillId = 0, BorderId = 0 }; // Default style : Mandatory | Style ID =0
CellFormat cellformat1 = new CellFormat(){FontId = 1};
CellFormats cellformats = new CellFormats();
cellformats.Append(cellformat0);
cellformats.Append(cellformat1);
ss.Append(fonts);
ss.Append(fills);
ss.Append(borders);
ss.Append(cellformats);
return ss;
}

Categories