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);
Related
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("سلام");
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/.
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;
}
I am trying to create reports in my asp.net MVC3 application after a lot of search I found many blog posts talks about ITextSharp to convert my Html/Razor to Pdf I am trying to parse razor view to get PDf as follows
public void Render(ViewContext viewContext, TextWriter writer)
{
var doc = new Document();
// associate output with response stream
var pdfWriter = PdfWriter.GetInstance(doc, viewContext.HttpContext.Response.OutputStream);
pdfWriter.CloseStream = false;
viewContext.HttpContext.Response.ContentType = "application/pdf";
viewContext.HttpContext.Response.ContentEncoding = System.Text.Encoding.UTF8;
// generate view into string
var sb = new System.Text.StringBuilder();
TextWriter tw = new System.IO.StringWriter(sb);
_result.View.Render(viewContext, tw);
var resultCache = sb.ToString();
//Path to our font
string arialuniTff = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIALUNI.TTF");
//Register the font with iTextSharp
iTextSharp.text.FontFactory.Register(arialuniTff);
//Create a new stylesheet
iTextSharp.text.html.simpleparser.StyleSheet ST = new iTextSharp.text.html.simpleparser.StyleSheet();
//Set the default body font to our registered font's internal name
ST.LoadTagStyle(HtmlTags.BODY, HtmlTags.FACE, "Arial Unicode MS");
//Set the default encoding to support Unicode characters
ST.LoadTagStyle(HtmlTags.BODY, HtmlTags.ENCODING, BaseFont.IDENTITY_H);
//Parse our HTML using the stylesheet created above
List<IElement> list = HTMLWorker.ParseToList(new StringReader(resultCache), ST);
doc.Open();
//Loop through each element, don't bother wrapping in P tags
foreach (var element in list)
{
doc.Add(element);
}
doc.Close();
pdfWriter.Close();
}
the result of that code is
which is not correct, the arabic word should be "محمد". so what I need is to set document direction to be from right to left
EDIT
Thanks to #Romulus
I made a little changes to his code i just replaced adding element to PdfPCell to looping on my Html and set some attributes
//Loop through each element, don't bother wrapping in P tags
foreach (var element in list)
{
//Create a cell and add text to it
//PdfPCell text = new PdfPCell(new Phrase(element.ToString(), f));
//Ensure that wrapping is on, otherwise Right to Left text will not display
//text.NoWrap = false;
//Add the cell to the table
//table.AddCell(text);
if (element is iTextSharp.text.pdf.PdfPTable)
{
table = (iTextSharp.text.pdf.PdfPTable)element;
table.DefaultCell.NoWrap = false;
table.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
foreach (PdfPRow row in table.Rows)
{
foreach (PdfPCell cell in row.GetCells())
{
cell.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
cell.NoWrap = false;
}
}
}
}
That's working for me now well Thanks :)
You need to use container elements which support RunDirection, such as ColumnText or PdfPCell and then set their element.RunDirection = PdfWriter.RUN_DIRECTION_RTL
List<IElement> list = HTMLWorker.ParseToList(new StringReader(resultCache), ST);
doc.Open();
//Use a table so that we can set the text direction
PdfPTable table = new PdfPTable(1);
//Ensure that wrapping is on, otherwise Right to Left text will not display
table.DefaultCell.NoWrap = false;
table.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
//Loop through each element, don't bother wrapping in P tags
foreach (var element in list)
{
//Create a cell and add text to it
PdfPCell text = new PdfPCell(new Phrase(element, font));
//Ensure that wrapping is on, otherwise Right to Left text will not display
text.NoWrap = false;
//Add the cell to the table
table.AddCell(text);
}
//Add the table to the document
document.Add(table);
doc.Close();
pdfWriter.Close();
For addition reference, have a look at this sample.
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.