How to make excel work sheet header row bold using OpenXML - c#

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;
}

Related

How to add colour to particular excel columns based on conditions using openxml?

I'm generating an excel sheet and I want to color the excel columns based on conditions. Now my all excel columns get red colors. I want to color only particular column names.
I'm using open XML for generating excel, is there any way to find the cells to apply color
using (SpreadsheetDocument document = SpreadsheetDocument.Create(path, SpreadsheetDocumentType.Workbook))
{
WorkbookPart workbookPart = document.AddWorkbookPart();
workbookPart.Workbook = new Workbook();
WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet();
Sheets sheets = workbookPart.Workbook.AppendChild(new Sheets());
Sheet sheet = new Sheet() { Id = workbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "Template" };
sheets.Append(sheet);
var 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");
var fills = new Fills() { Count = 5U };
var fonts = new Fonts() { Count = 1U, KnownFonts = true };
// var cellFormats = new CellFormats();
Font font = new Font();
font.Append(new Color() { Rgb = "ff0000" });
fonts.Append(font);
// cellFormats.AppendChild(new CellFormat() { FontId = 0U });
stylesheet.Append(fonts);
stylesheet.Append(fills);
//stylesheet.Append(cellFormats);
//stylesheet.Append(fill);
var stylePart = workbookPart.AddNewPart<WorkbookStylesPart>();
stylePart.Stylesheet = stylesheet;
stylePart.Stylesheet.Save();
workbookPart.Workbook.Save();
SheetData sheetData = worksheetPart.Worksheet.AppendChild(new SheetData());
// Constructing header
Row row = new Row();
foreach (DataExchangeDefinition a in importColList)
{
defnExist = true;
if (a.MustFieldYN == true)
{
row.Append(
ConstructCell(a.FieldCaption, CellValues.String));
}
else
{
row.Append(
ConstructCell(a.FieldCaption, CellValues.String));
}
}
if (defnExist == false)
{
row.Append(
ConstructCell("Excel Template Definition Missing", CellValues.String));
}
// Insert the header row to the Sheet Data
sheetData.AppendChild(row);
// Inserting each employee
worksheetPart.Worksheet.Save();
}
Here is construct cell method
private Cell ConstructCell(string value, CellValues dataType)
{
Cell c = new Cell()
{
CellValue = new CellValue(value),
DataType = new EnumValue<CellValues>(dataType)
//StyleIndex=0U
};
return c;
}
Is there any way to solve this?
1) Add style sheet to your WorkBookPart
WorkbookPart workbookPart = document.AddWorkbookPart();
workbookPart.Workbook = new Workbook();
WorkbookStylesPart stylePart = workbookPart.AddNewPart<WorkbookStylesPart>();
stylePart.Stylesheet = GenerateStylesheet();
stylePart.Stylesheet.Save();
Note: Add above WorkbookStylesPart code just below the WorkbookPart otherwise you can't get it to work.
2) Add below function that return stylesheet,
private Stylesheet GenerateStylesheet()
{
Stylesheet styleSheet = null;
Fonts fonts = new Fonts(
new Font( // Index 0 - default
new FontSize() { Val = 10 }
),
new Font( // Index 1 - header
new FontSize() { Val = 10 },
new Bold(),
new Color() { Rgb = "FFFFFF" }
));
Fills fills = new Fills(
new Fill(new PatternFill() { PatternType = PatternValues.None }), // Index 0 - default
new Fill(new PatternFill() { PatternType = PatternValues.Gray125 }), // Index 1 - default
new Fill(new PatternFill(new ForegroundColor { Rgb = new HexBinaryValue() { Value = "66666666" } })
{ PatternType = PatternValues.Solid }) // Index 2 - header
);
Borders borders = new Borders(
new Border(), // index 0 default
new Border( // index 1 black border
new LeftBorder(new Color() { Auto = true }) { Style = BorderStyleValues.Thin },
new RightBorder(new Color() { Auto = true }) { Style = BorderStyleValues.Thin },
new TopBorder(new Color() { Auto = true }) { Style = BorderStyleValues.Thin },
new BottomBorder(new Color() { Auto = true }) { Style = BorderStyleValues.Thin },
new DiagonalBorder())
);
CellFormats cellFormats = new CellFormats(
new CellFormat(), // default
new CellFormat { FontId = 0, FillId = 0, BorderId = 1, ApplyBorder = true }, // body
new CellFormat { FontId = 1, FillId = 2, BorderId = 1, ApplyFill = true } // header
);
styleSheet = new Stylesheet(fonts, fills, borders, cellFormats);
return styleSheet;
}
3) And your ConstructCell method,
private Cell ConstructCell(string value, CellValues dataType, uint styleIndex = 0)
{
return new Cell()
{
CellValue = new CellValue(value),
DataType = new EnumValue<CellValues>(dataType),
StyleIndex = styleIndex
};
}
4) And call your above method like
If you dont want to apply style then use below
ConstructCell(a.FieldCaption, CellValues.String));
And if you want to apply style on body cell then use below
ConstructCell(a.FieldCaption, CellValues.String, 1);
And if you want to apply style on header cell then use below
ConstructCell(a.FieldCaption, CellValues.String, 2);

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/.

Create Excel file with style tag using OpenXmlWriter SAX

I am trying to write an Excel Xlsx spreadsheet with styling using OpenXmlWriter (SAX).
I am able to create the file with rows and columns (populate them as strings).
I am looking for a simple code on how to make the first row (header) with bold font.
I do not have a template file to start with as the file will be dynamic.
I found a few articles on how to add WorkbookStylesPart, but they are all using the DOM. As i need to write large number of rows, the DOM will not work for me.
Could anyone point me at the right direction?
Simple code to add a header row as bold when using WriteStartElement and OpenXmlAttribute.
Thanks, odansky
Adding StyleSheet is one time work. After that you just need to simply refer the defined style ID when creating new cells.
Hot to add a stylesheet to spreadsheet [With Bold text style]
private WorkbookStylesPart AddStyleSheet(SpreadsheetDocument spreadsheet)
{
WorkbookStylesPart stylesheet = spreadsheet.WorkbookPart.AddNewPart<WorkbookStylesPart>();
Stylesheet workbookstylesheet = 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);
// <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;
}
Now when you create a cell do following to refer to the Bold text
Cell c1 = new Cell(){StyleIndex = Convert.ToUInt32(1)}; // Assign our defined style with Bold text ; Style ID 1
Additional Note : You need to add stylesheet after adding workbookpart of the spreadsheet.
More regarding SAX approach : You can define styles when you first create the template file which you gonna open to insert data cells. And when adding data cells refer to the defined styles using ID.
A simple working spreadsheet with style (MSDN)
public static void CreateSpreadsheetWorkbook(string filepath)
{
// Create a spreadsheet document by supplying the filepath.
// By default, AutoSave = true, Editable = true, and Type = xlsx.
SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(filepath, SpreadsheetDocumentType.Workbook);
// Add a WorkbookPart to the document.
WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
AddStyleSheet(spreadsheetDocument) // <== Adding stylesheet using above function
// Add a WorksheetPart to the WorkbookPart.
WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
// Add Sheets to the Workbook.
Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());
// Append a new worksheet and associate it with the workbook.
Sheet sheet = new Sheet() { Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "mySheet" };
sheets.Append(sheet);
workbookpart.Workbook.Save();
// Close the document.
spreadsheetDocument.Close();
}
You set the style index the same way you set the datatype for the cell:
oxa.Add(new OpenXmlAttribute("s", null, "1"));

Format Font Inside Table OpenXML 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.

Write excel using excel package with formatting

I want to write excel file using excel package from System.Data.DataTable
and need to format some cells in excel file like back ground color.
How can I do that?
Although you may use Interop calls to create an excel file, I prefer solutions without it. According to your given details I found a solution based on OpenXML. No need for Interop but you have to learn the according objectModel from openXML. What you need before you can start:
Download OpenXML SDK and install it from microsoft
Go to openXmlDeveloper.org and learn how to use openXml to create excelFiles
Have a look at several ressources in the web concerning how to access/read/write excelFiles with openXml (such as SO_Question1, social.msdn.microsoft.com_example, Blog1 and SO_Question2)
Afterwards within your project...
Add reference to DocumentFormat.OpenXML library (search your computer, somewhat like C:\Program Files (x86)\Open XML SDK\V2.0\lib\DocumentFormat.OpenXml.dll)
Add reference to WindowBase
And than you are ready to use this piece of code:
// important namespaces
using System.IO.Packaging;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Spreadsheet;
using Excel = DocumentFormat.OpenXml.Office2010.Excel;
static void Main(string[] args)
{
// created a demoTable with id column and five string columns with arbitrary values
DataTable demoTable = CreateDemoTable();
CreateWorkbook(#"c:\ExcelAndStyles.xlsx", demoTable);
}
private static void CreateWorkbook(string fileName, DataTable table)
{
try
{
if (File.Exists(fileName))
File.Delete(fileName);
using (SpreadsheetDocument xl = SpreadsheetDocument.Create(fileName, 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();
WorkbookStylesPart wbsp = wbp.AddNewPart<WorkbookStylesPart>();
// add styles to sheet
wbsp.Stylesheet = CreateStylesheet();
wbsp.Stylesheet.Save();
// generate data (row&cells) and add it to workbook
SheetData sd = CreateSheetData(table);
ws.Append(sd);
wsp.Worksheet = ws;
wsp.Worksheet.Save();
Sheets sheets = new Sheets();
Sheet sheet = new Sheet();
sheet.Name = table.TableName;
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();
}
}
catch (Exception e)
{ // do some errorHandling here }
}
private static Stylesheet CreateStylesheet()
{
// add namespace info
Stylesheet stylesheet1 = new Stylesheet() { MCAttributes = new MarkupCompatibilityAttributes() { Ignorable = "x14ac" } };
stylesheet1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
stylesheet1.AddNamespaceDeclaration("x14ac", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac");
// fonts
Fonts fonts1 = new Fonts() { Count = (UInt32Value)1U, KnownFonts = true };
Font font1 = new Font();
FontSize fontSize1 = new FontSize() { Val = 11D };
Color color1 = new Color() { Theme = (UInt32Value)1U };
FontName fontName1 = new FontName() { Val = "Calibri" };
FontFamilyNumbering fontFamilyNumbering1 = new FontFamilyNumbering() { Val = 2 };
FontScheme fontScheme1 = new FontScheme() { Val = FontSchemeValues.Minor };
font1.Append(fontSize1);
font1.Append(color1);
font1.Append(fontName1);
font1.Append(fontFamilyNumbering1);
font1.Append(fontScheme1);
fonts1.Append(font1);
// fillColor
Fills fills1 = new Fills() { Count = (UInt32Value)5U };
// FillId = 0
Fill fill1 = new Fill();
PatternFill patternFill1 = new PatternFill() { PatternType = PatternValues.None };
fill1.Append(patternFill1);
// FillId = 1
Fill fill2 = new Fill();
PatternFill patternFill2 = new PatternFill() { PatternType = PatternValues.Gray125 };
fill2.Append(patternFill2);
// FillId = 2,RED
Fill fill3 = new Fill();
PatternFill patternFill3 = new PatternFill() { PatternType = PatternValues.Solid };
ForegroundColor foregroundColor1 = new ForegroundColor() { Rgb = "FFFF0000" };
BackgroundColor backgroundColor1 = new BackgroundColor() { Indexed = (UInt32Value)64U };
patternFill3.Append(foregroundColor1);
patternFill3.Append(backgroundColor1);
fill3.Append(patternFill3);
// FillId = 3,BLUE
Fill fill4 = new Fill();
PatternFill patternFill4 = new PatternFill() { PatternType = PatternValues.Solid };
ForegroundColor foregroundColor2 = new ForegroundColor() { Rgb = "FF0070C0" };
BackgroundColor backgroundColor2 = new BackgroundColor() { Indexed = (UInt32Value)64U };
patternFill4.Append(foregroundColor2);
patternFill4.Append(backgroundColor2);
fill4.Append(patternFill4);
// FillId = 4,YELLO
Fill fill5 = new Fill();
PatternFill patternFill5 = new PatternFill() { PatternType = PatternValues.Solid };
ForegroundColor foregroundColor3 = new ForegroundColor() { Rgb = "FFFFFF00" };
BackgroundColor backgroundColor3 = new BackgroundColor() { Indexed = (UInt32Value)64U };
patternFill5.Append(foregroundColor3);
patternFill5.Append(backgroundColor3);
fill5.Append(patternFill5);
fills1.Append(fill1); // 0U
fills1.Append(fill2); // 1U
fills1.Append(fill3); // 2U
fills1.Append(fill4); // 3U
fills1.Append(fill5); // 4U
// border styles
Borders borders1 = new Borders() { Count = (UInt32Value)1U };
Border border1 = new Border();
LeftBorder leftBorder1 = new LeftBorder();
RightBorder rightBorder1 = new RightBorder();
TopBorder topBorder1 = new TopBorder();
BottomBorder bottomBorder1 = new BottomBorder();
DiagonalBorder diagonalBorder1 = new DiagonalBorder();
border1.Append(leftBorder1);
border1.Append(rightBorder1);
border1.Append(topBorder1);
border1.Append(bottomBorder1);
border1.Append(diagonalBorder1);
borders1.Append(border1);
// cellFormats
CellStyleFormats cellStyleFormats1 = new CellStyleFormats() { Count = (UInt32Value)1U };
CellFormat cellFormat1 = new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)0U, FillId = (UInt32Value)0U, BorderId = (UInt32Value)0U };
cellStyleFormats1.Append(cellFormat1);
CellFormats cellFormats1 = new CellFormats() { Count = (UInt32Value)4U };
// see a few lines above - refer to: fills1.Append(XXXX);
// see also ApplyFill = true!!
CellFormat cellFormat2 = new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)0U, FillId = (UInt32Value)0U, BorderId = (UInt32Value)0U, FormatId = (UInt32Value)0U };
CellFormat cellFormat3 = new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)0U, FillId = (UInt32Value)2U, BorderId = (UInt32Value)0U, FormatId = (UInt32Value)0U, ApplyFill = true };
CellFormat cellFormat4 = new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)0U, FillId = (UInt32Value)3U, BorderId = (UInt32Value)0U, FormatId = (UInt32Value)0U, ApplyFill = true };
CellFormat cellFormat5 = new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)0U, FillId = (UInt32Value)4U, BorderId = (UInt32Value)0U, FormatId = (UInt32Value)0U, ApplyFill = true };
cellFormats1.Append(cellFormat2); // fillId 0U --- cellFormat Index 0
cellFormats1.Append(cellFormat3); // fillId 2U --- cellFormat Index 1
cellFormats1.Append(cellFormat4); // fillId 3U --- cellFormat Index 2
cellFormats1.Append(cellFormat5); // fillId 4U --- cellFormat Index 3
// cellStyles
CellStyles cellStyles1 = new CellStyles() { Count = (UInt32Value)1U };
CellStyle cellStyle1 = new CellStyle() { Name = "Normal", FormatId = (UInt32Value)0U, BuiltinId = (UInt32Value)0U };
cellStyles1.Append(cellStyle1);
DifferentialFormats differentialFormats1 = new DifferentialFormats() { Count = (UInt32Value)0U };
TableStyles tableStyles1 = new TableStyles() { Count = (UInt32Value)0U, DefaultTableStyle = "TableStyleMedium2", DefaultPivotStyle = "PivotStyleMedium9" };
// extensions
StylesheetExtensionList stylesheetExtensionList1 = new StylesheetExtensionList();
StylesheetExtension stylesheetExtension1 = new StylesheetExtension() { Uri = "{EB79DEF2-80B8-43e5-95BD-54CBDDF9020C}" };
stylesheetExtension1.AddNamespaceDeclaration("x14", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main");
Excel.SlicerStyles slicerStyles1 = new Excel.SlicerStyles() { DefaultSlicerStyle = "SlicerStyleLight1" };
stylesheetExtension1.Append(slicerStyles1);
stylesheetExtensionList1.Append(stylesheetExtension1);
// add all formats/styles to stylesheet
stylesheet1.Append(fonts1);
stylesheet1.Append(fills1);
stylesheet1.Append(borders1);
stylesheet1.Append(cellStyleFormats1);
stylesheet1.Append(cellFormats1);
stylesheet1.Append(cellStyles1);
stylesheet1.Append(differentialFormats1);
stylesheet1.Append(tableStyles1);
stylesheet1.Append(stylesheetExtensionList1);
return stylesheet1;
}
private static SheetData CreateSheetData(DataTable table)
{
SheetData sheetData = new SheetData();
for (int rowIndex = 0; rowIndex < table.Rows.Count; rowIndex++)
{
DataRow dataRow = table.Rows[rowIndex];
Row row = new Row() { RowIndex = new UInt32Value((uint)(rowIndex + 1)) };
for (int colIndex = 0; colIndex < dataRow.ItemArray.Length; colIndex++)
{
object value = dataRow[colIndex].ToString();
Cell cell = new Cell();
cell.CellReference = ((char)(colIndex + 65)).ToString() + (rowIndex+1).ToString();
// assigned simple red background style
// have a deeper look in CreateStylesheet for details what 1U contains
// for demo purposes may choose 2U and 3U too
cell.StyleIndex = (UInt32Value)1U;
// for demo purposes, treat all values as string
cell.DataType = CellValues.String;
cell.CellValue = new CellValue(table.Rows[rowIndex][colIndex].ToString());
row.Append(cell);
}
sheetData.Append(row);
}
return sheetData;
}
Most of this code has been taken out of several sites listed above! I adopted it and changed it to fit your question. This example code worked for me to create an excelFile containing several rows and columns with differen values and styles.
Hope that helps!

Categories