Apply OpenXML excel number formatcode to string value in C# - c#

Using OpenXML in C#, does anybody knows how to apply an excel number formatcode - for instance (* #,##0.00);(* (#,##0.00);(* "-"??);(#_) - to a string value?
Example, if I have a value "10.52982" I should obtain "10.53"
Thanks
PS I don't want to use the Microsoft.Office.Interop.Excel assembly which provides WorksheetFunction.Text function

Try this:
//Create Document
SpreadsheetDocument googleSpreadSheet = SpreadsheetDocument.Create(GoogleSpreadhSheetStream, SpreadsheetDocumentType.Workbook);
WorkbookPart cWorkbookPart = googleSpreadSheet.AddWorkbookPart();
//Create stylesheet
WorkbookStylesPart spStyles = cWorkbookPart.AddNewPart<WorkbookStylesPart>();
spStyles.Stylesheet = new Stylesheet();
spStyles.Stylesheet.NumberingFormats = new NumberingFormats();
uint iExcelIndex = 164;
//Create format
NumberingFormat nf2decimal = new NumberingFormat();
nf2decimal.NumberFormatId = UInt32Value.FromUInt32(3453);//UInt32Value.FromUInt32(iExcelIndex++);
nf2decimal.FormatCode = StringValue.FromString("0.00");
spStyles.Stylesheet.NumberingFormats.Append(nf2decimal);
//Create cellFormat
CellFormat numFormat = new CellFormat();
numFormat.FormatId = 0;
numFormat.FillId = 0;
numFormat.BorderId = 0;
numFormat.FormatId = 0;
numFormat.NumberFormatId = nf2decimal.NumberFormatId;
numFormat.ApplyNumberFormat = BooleanValue.FromBoolean(true);
//Apped cellformat for cells
spStyles.Stylesheet.CellFormats.AppendChild<CellFormat>(cellFormat);
//update styles and format count
spStyles.Stylesheet.NumberingFormats.Count = UInt32Value.FromUInt32((uint)spStyles.Stylesheet.NumberingFormats.ChildElements.Count);
spStyles.Stylesheet.CellFormats.Count = UInt32Value.FromUInt32((uint)spStyles.Stylesheet.CellFormats.ChildElements.Count);
//save the changes to the stylesheet
spStyles.Stylesheet.Save();
googleSpreadSheet.WorkbookPart.Workbook.Save();
And when setting the value of the cell, use the format index. Since I just added one, the format index should be 1
SheetData cSheetData = (SheetData)GetWorkSheet(sheetId).Where(x => x.LocalName == "sheetData").First();
Row currentRow = new Row();
Cell cell = new Cell();
currentRow.RowIndex = Convert.ToUInt32(cSheetData.ChildElements.Count()) + 1;
cell.DataType = new EnumValue<CellValues>(CellValues.Number);
cell.CellValue = new CellValue(value.Value);
cell.StyleIndex = 1;
cell.CellReference = nextCol + rowIndex;
currentRow.AppendChild(cell);
cSheetData.Append(currentRow);
GetWorkSheet(sheetId).Save(); //this returns the reference to my sheet doc to save it
Hope this helps you out

Related

How do I split data across multiple spreadsheets in Excel using C# code?

I am trying to create an application that can extract a ton of data from a txt file 3000+ lines.
I have already filtered the data etc and I am able to write everything into the excel spreadsheet in the correct way. My problem is that I want to split the data over multiple sheets and limit each sheet to a specific number of data rows (The exact value is a number chosen between 100-1000)
I have ended up with an output that creates the correct number of sheets, but it outputs all the lines of data into all the sheets instead of splitting them up over all the sheets.
For clarity:
Example: I have 950 lines of data. Thus the output should be 100 data rows in 8 sheets and the 9th should have the last 50.
What I currently get is: 950 data rows in all 9 sheets.
Here is my code that controls the Excel creation.
using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(filename, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
{
WorkbookPart workbookPart = spreadsheetDocument.AddWorkbookPart();
workbookPart.Workbook = new Workbook();
WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
var workSheet = worksheetPart.Worksheet;
Sheets sheets = workbookPart.Workbook.AppendChild(new Sheets());
for (int i = 0; i < Amount; i++)
{
Sheet sheet = new Sheet()
{
Id = workbookPart.GetIdOfPart(worksheetPart),
SheetId = ((uint)(i + 1)),
Name = "Data" + (i + 1)
};
sheets.Append(sheet);
var HeadRow = workSheet.GetFirstChild<SheetData>().AppendChild(new Row());//new Row
HeadRow.AppendChild(new Cell() { CellValue = new CellValue("Type"), DataType = new EnumValue<CellValues>(CellValues.String) });
HeadRow.AppendChild(new Cell() { CellValue = new CellValue("Description"), DataType = new EnumValue<CellValues>(CellValues.String) });
HeadRow.AppendChild(new Cell() { CellValue = new CellValue("Time"), DataType = new EnumValue<CellValues>(CellValues.String) });
HeadRow.AppendChild(new Cell() { CellValue = new CellValue("Date"), DataType = new EnumValue<CellValues>(CellValues.String) });
for (int j = 0 + (i * (int)OrgAmount); j < ((i + 1) * (int)OrgAmount); j++)//Rows
{
if (j == LineCount)
{
break;
}
var row = workSheet.GetFirstChild<SheetData>().AppendChild(new Row());//new Row
var cell1 = row.AppendChild(new Cell());//Type
var cell2 = row.AppendChild(new Cell());//Description
var cell3 = row.AppendChild(new Cell());//Time
var cell4 = row.AppendChild(new Cell());//Date
cell1.CellValue = new CellValue(LineType[j]);
cell1.DataType = new EnumValue<CellValues>(CellValues.String);
cell2.CellValue = new CellValue(LineDesc[j]);
cell2.DataType = new EnumValue<CellValues>(CellValues.String);
cell3.CellValue = new CellValue(LineTime[j]);
cell3.DataType = new EnumValue<CellValues>(CellValues.String);
cell4.CellValue = new CellValue(LineDate[j]);
cell4.DataType = new EnumValue<CellValues>(CellValues.String);
}
workbookPart.Workbook.Save();
}
spreadsheetDocument.Close();
}
Please help me since I don't know where I messed up.
I got it fixed myself in the end.
Here is what I did:
using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(filename, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
{
//Create workbook, workbookPart and sheets
WorkbookPart workbookPart = spreadsheetDocument.AddWorkbookPart();
workbookPart.Workbook = new Workbook();
Sheets sheets = workbookPart.Workbook.AppendChild(new Sheets());
for (int i = 0; i < Amount; i++)
{
//New worksheetPart, worksheet and sheet for each sheet to be addressed seperately
WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
var workSheet = worksheetPart.Worksheet;
//Dynamically create a sheet according to options chosen in form
Sheet sheet = new Sheet()
{
Id = workbookPart.GetIdOfPart(worksheetPart),
SheetId = ((uint)(i + 1)),
Name = "Data" + (i + 1)
};
//Header row creation
var HeadRow = workSheet.GetFirstChild<SheetData>().AppendChild(new Row());//new Row
HeadRow.AppendChild(new Cell() { CellValue = new CellValue("Type"), DataType = new EnumValue<CellValues>(CellValues.String) });
HeadRow.AppendChild(new Cell() { CellValue = new CellValue("Description"), DataType = new EnumValue<CellValues>(CellValues.String) });
HeadRow.AppendChild(new Cell() { CellValue = new CellValue("Time"), DataType = new EnumValue<CellValues>(CellValues.String) });
HeadRow.AppendChild(new Cell() { CellValue = new CellValue("Date"), DataType = new EnumValue<CellValues>(CellValues.String) });
for (int j = 0 + (i * (int)OrgAmount); j < ((i + 1) * (int)OrgAmount); j++)//Rows
{
if (j == LineCount)//If final line is reached before loop end, then break loop
{
break;
}
//Initialise new row cells
var row = workSheet.GetFirstChild<SheetData>().AppendChild(new Row());//new Row
var cell1 = row.AppendChild(new Cell());//Type
var cell2 = row.AppendChild(new Cell());//Description
var cell3 = row.AppendChild(new Cell());//Time
var cell4 = row.AppendChild(new Cell());//Date
//Write data to cells, extracted from text file
cell1.CellValue = new CellValue(LineType[j]);
cell1.DataType = new EnumValue<CellValues>(CellValues.String);
cell2.CellValue = new CellValue(LineDesc[j]);
cell2.DataType = new EnumValue<CellValues>(CellValues.String);
cell3.CellValue = new CellValue(LineTime[j]);
cell3.DataType = new EnumValue<CellValues>(CellValues.String);
cell4.CellValue = new CellValue(LineDate[j]);
cell4.DataType = new EnumValue<CellValues>(CellValues.String);
}
sheets.Append(sheet);//Append the written sheet to workbook sheets
}
workbookPart.Workbook.Save();//save workbook
spreadsheetDocument.Close();//Close document
}

How can I fit all columns on one page in a spreadsheet?

I have exported the report to Excel and it works fine, but when I print the file the width of the spreadsheet doesn't fit all column into one page. For this to happen I have to change the Page Layout, and set the scaling to fit 1 on width and 43 tall. How can I get this from code?
using (var workbook = SpreadsheetDocument.Create(Savepath, SpreadsheetDocumentType.Workbook))
{
var workbookPart = workbook.AddWorkbookPart();
workbook.WorkbookPart.Workbook = new Workbook();
workbook.WorkbookPart.Workbook.Sheets = new Sheets();
//declare our MergeCells here
MergeCells mergeCells = null;
foreach (DataRow dsrow in table.Rows)
{
int innerColIndex = 0;
rowIndex++;
Row newRow = new Row();
foreach (String col in columns)
{
Stylesheet stylesheet1 = new Stylesheet();
Cell cell = new Cell();
cell.DataType = CellValues.String;
cell.CellValue = new CellValue(dsrow[col].ToString());
cell.CellReference = excelColumnNames[innerColIndex] + rowIndex.ToString();
if (table.TableName == "Work Order Report")
{
string cellNameWorkOrder = dsrow[col].ToString();
if (cellNameWorkOrder == "POSTER: 10% MUST HAVE APPROACH AND CLOSE-UP SHOTS - PHOTO OF EACH CREATIVE" || cellNameWorkOrder == "BULLETINS: 100% CLOSE-UP AND APPROACH OF EACH UNIT")
{
if (mergeCells == null)
mergeCells = new MergeCells();
var cellAddress = cell.CellReference;
var cellAddressTwo = "I" + rowIndex.ToString();
mergeCells.Append(new MergeCell() { Reference = new StringValue(cellAddress + ":" + cellAddressTwo) });
}
}
newRow.AppendChild(cell);
innerColIndex++;
}
sheetData.AppendChild(newRow);
}
//add the mergeCells to the worksheet if we have any
if (mergeCells != null)
sheetPart.Worksheet.InsertAfter(mergeCells, sheetPart.Worksheet.Elements<SheetData>().First());
}
workbook.WorkbookPart.Workbook.Save();
}
The excel report looks like https://www.screencast.com/t/CCMR96Mw7u when I print now its like https://www.screencast.com/t/MkTpDc98RD0l ,https://www.screencast.com/t/MRyzpEiFICM the expected result is https://www.screencast.com/t/ztgvm6mISSwp
In order to achieve this you need to do two things. Firstly, you need to add a PageSetupProperties instance to a SheetProperties instance which in turn should get added to your Worksheet. The PageSetupProperties has a FitToPage property which is the part that sets the radio button in Excel to "Fit to".
Next, you need to use the PageSetup class in order to set the width and height required. This is done via the FitToWidth and FitToHeight properties. The PageSetup also needs to be added to the Worksheet.
Note that the order of the elements is important, you can see the correct order in the ECMA spec.
The following is a self contained example that adds one cell and then sets the properties the way that you need them:
using (SpreadsheetDocument myDoc = SpreadsheetDocument.Create(filename, SpreadsheetDocumentType.Workbook))
{
WorkbookPart workbookpart = myDoc.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
// Add a WorksheetPart to the WorkbookPart.
WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
SheetData sheetData = new SheetData();
//add a row
Row row = new Row();
row.RowIndex = 1;
//create a cell
Cell cell = new Cell();
cell.CellReference = "A1";
CellValue cellValue = new CellValue();
cellValue.Text = "123";
cell.Append(cellValue);
row.AppendChild(cell);
sheetData.AppendChild(row);
// Add a WorkbookPart to the document.
worksheetPart.Worksheet = new Worksheet(sheetData);
//this sets the "Fit to" radio in Excel.
//note this must come before the SheetData
SheetProperties sheetProperties = new SheetProperties();
PageSetupProperties pageSetupProperties = new PageSetupProperties() { FitToPage = true };
sheetProperties.Append(pageSetupProperties);
worksheetPart.Worksheet.InsertBefore(sheetProperties, sheetData);
// this changes the fit to width and height
PageSetup pageSetup = new PageSetup() { FitToWidth = 1, FitToHeight = 43 };
worksheetPart.Worksheet.AppendChild(pageSetup);
//append the sheets / sheet
Sheets sheets = myDoc.WorkbookPart.Workbook.AppendChild(new Sheets());
sheets.AppendChild(new Sheet()
{
Id = myDoc.WorkbookPart.GetIdOfPart(myDoc.WorkbookPart.WorksheetParts.First()),
SheetId = 1,
Name = "Sheet1"
});
}

apply style to excel file generated using office open xml C#

I've used Office OpenXML to generate XML file using windows service. The code works fine and excel file gets generated. But now I want to add some style to rows and cells. How can I achieve that?
The code I've used is:
if (thermoCoupleList.Count > 0)
{
FileInfo newFile = new FileInfo(filePath);
using (ExcelPackage xlPackage = new ExcelPackage(newFile))
{
ExcelWorksheet worksheet = xlPackage.Workbook.Worksheets.Add("ThermoCouples");
// write some titles into row 1
worksheet.Cell(1, 1).Value = "Thermocouple ID";
worksheet.Cell(1, 2).Value = "Calibration Done Date";
worksheet.Cell(1, 3).Value = "Calibration Due Date";
worksheet.Cell(1, 4).Value = "Company";
int col, row = 1;
foreach (Thermocouples tc1 in thermoCoupleList)
{
col = 1;
row = row + 1;
worksheet.Cell(row, col++).Value = Convert.ToString(tc1.ThermocoupleIdentification);
worksheet.Cell(row, col++).Value = tc1.CalibrationDoneDate;
worksheet.Cell(row, col++).Value = tc1.CalibrationDueDate;
worksheet.Cell(row, col++).Value = tc1.Company;
}
xlPackage.Save();
}
}
How can I achieve styling in Office OpenXML?
First of all you should add style to your sheet
Like this
private void AddStyles(Stylesheet styleSheet)
{
var patternFill = new PatternFill
{
PatternType = PatternValues.Solid,
ForegroundColor = new ForegroundColor { Rgb = "FFFF0000" },
BackgroundColor = new BackgroundColor { Indexed = 64U }
};
var fill = new Fill { PatternFill = patternFill };
styleSheet.Fills.AppendChild(fill);
}
Stylesheet object you can get for example in the following way
using (SpreadsheetDocument document = SpreadsheetDocument.Open(FilePath, true))
{
var styleSheet= document.WorkbookPart.WorkbookStylesPart.Stylesheet;
}
Every of your styles will have some index. You can assign this style index to your cell. Use this property
DocumentFormat.OpenXml.Spreadsheet.Cell.StyleIndex

Shared String Table return null when reading created excel (Open xml)

I am creating excel file using open xml sdk. And I want to read it using open xml. When i want to read it i am getting error at this line
SharedStringTablePart sstpart = workbookPart.GetPartsOfType<SharedStringTablePart>().First();it return null
if I open excel file and save again.It creates shared string table and it run.
Reading from excel
#region OpenFile
public void OpenFile(string directory)
{
try
{
fs = new FileStream(directory, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
doc = SpreadsheetDocument.Open(fs, false);
}
catch (FileNotFoundException ex)
{
string exception = string.Format("Doya bulunamadı{0}", directory);
throw new ApplicationException(exception);
}
}
#endregion
#region GetWorkSheet
public void AssignWorkSheet(int sheetID)
{
if (fs == null || doc == null)
throw new ApplicationException("Dosya açılamadı");
WorkbookPart workbookPart = doc.WorkbookPart;
SharedStringTablePart sstpart = workbookPart.GetPartsOfType<SharedStringTablePart>().First();
sst = sstpart.SharedStringTable;
var workbook = workbookPart.Workbook;
var sheets = workbook.Descendants<Sheet>();
var sheetINVOICE = sheets.ElementAt(sheetID);
var worksheetPartINVOICE = (WorksheetPart)workbookPart.GetPartById(sheetINVOICE.Id);
WorkSheet = worksheetPartINVOICE.Worksheet;
//return sheetInvoice;
}
#endregion
It creates an write some text and numeric value with below code
var fileName = string.Format(#"C:\Sonuc\{0}\{1}.xlsx", systemType.ToString(), systemTypeEnum.ToString() + "_" + fileType.ToString());
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();
SheetData sd = new SheetData();
//int rowCount = 1;
DocumentFormat.OpenXml.UInt32Value rowCount = 1;
foreach (var item in resultList)
{
rowCount = rowCount + 1;
Row r3 = new Row() { RowIndex = rowCount };
Cell c6 = new Cell();
c6.DataType = CellValues.String;
c6.CellValue = new CellValue(item.BusinessPartner);
r3.Append(c6);
Cell c7 = new Cell();
c7.DataType = CellValues.Number;
c7.CellValue = new CellValue(item.VKN);
r3.Append(c7);
Cell c8 = new Cell();
c8.DataType = CellValues.Number;
c8.CellValue = new CellValue(item.InvoiceCount.ToString());
r3.Append(c8);
Cell c9 = new Cell();
c9.DataType = CellValues.Number;
c9.CellValue = new CellValue(item.TaxTotalAmount.ToString());
r3.Append(c9);
sd.Append(r3);
}
ws.Append(sd);
wsp.Worksheet = ws;
wsp.Worksheet.Save();
Sheets sheets = new Sheets();
Sheet sheet = new Sheet();
sheet.Name = "Sheet1";
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();
By default, MS EXCEL saves String values using the SharedStringTablePart. It's why your code seems working when you open and save the file with MS EXCEL.
But here, when you create the file, you define the Cell.Datatype to CellValues.String (instead of CellValues.SharedString)
c6.DataType = CellValues.String;
When Cell.Datatype is CellValues.String, you must read the value by reading the Cell.CellValue property.
To save the String values using SharedStringPart, please refer to online documentation:
How to: Insert Text into a Cell in a Spreadsheet Document
How to: Retrieve the Values of Cells in a Spreadsheet Document

OpenXML library save excel file

I have the following code and its not saving the values to cell and also in file. It shows value in cell.cellvalue field but its not writing it to excel. I have no idea how to save the file. I used OpenXml-SDK and I am writing datatable values to each cell/row of created spreadsheet document.
using (SpreadsheetDocument ssd=SpreadsheetDocument.Open(Server.MapPath(#"\ExcelPackageTemplate.xlsx"),true))
{
WorkbookPart wbPart = ssd.WorkbookPart;
WorksheetPart worksheetPart = wbPart.WorksheetParts.First();
SheetData sheetdata = worksheetPart.Worksheet.GetFirstChild<SheetData>();
string[] headerColumns = new string[] { dt.Columns[0].ColumnName, dt.Columns[1].ColumnName,dt.Columns[2].ColumnName };
DocumentFormat.OpenXml.Spreadsheet.Row r = new DocumentFormat.OpenXml.Spreadsheet.Row();
int RowIndexer = 1;
//int colInd=0;
r.RowIndex = (UInt32)RowIndexer;
string test = ColumnName(RowIndexer);
foreach (DataColumn dc in dt.Columns)
{
DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
cell.CellReference = test+RowIndexer;
cell.DataType = CellValues.InlineString;
cell.InlineString = new InlineString(new Text(dc.ColumnName.ToString()));
DocumentFormat.OpenXml.Spreadsheet.CellValue value = new DocumentFormat.OpenXml.Spreadsheet.CellValue();
r.AppendChild(cell);
// colInd++;
}
//r.RowIndex = (UInt32)RowIndexer;
RowIndexer = 2;
foreach (DataRow dr in dt.Rows)
{
DocumentFormat.OpenXml.Spreadsheet.Row Row = new DocumentFormat.OpenXml.Spreadsheet.Row();
string Index = ColumnName(RowIndexer);
Row.RowIndex = (UInt32)RowIndexer;
foreach (object value in dr.ItemArray)
{
DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
cell.DataType = CellValues.InlineString;
cell.InlineString = new InlineString(new Text(value.ToString()));
cell.CellReference = Index+RowIndexer;
// cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(value.ToString());
Row.AppendChild(cell);
}
RowIndexer++;
}
worksheetPart.Worksheet.Save();
wbPart.Workbook.Save();
ssd.Close();
Try this:
using (SpreadsheetDocument ssd = SpreadsheetDocument.Open(Server.MapPath(#"\ExcelPackageTemplate.xlsx"), true))
{
WorkbookPart wbPart = ssd.WorkbookPart;
WorksheetPart worksheetPart = wbPart.WorksheetParts.First();
SheetData sheetdata = worksheetPart.Worksheet.GetFirstChild<SheetData>();
string[] headerColumns = new string[] { dt.Columns[0].ColumnName, dt.Columns[1].ColumnName, dt.Columns[2].ColumnName };
DocumentFormat.OpenXml.Spreadsheet.Row r = new DocumentFormat.OpenXml.Spreadsheet.Row();
DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
int RowIndexer = 1;
int ColumnIndexer = 1;
r.RowIndex = (UInt32)RowIndexer;
foreach (DataColumn dc in dt.Columns)
{
cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
cell.CellReference = ColumnName(ColumnIndexer) + RowIndexer;
cell.DataType = CellValues.InlineString;
cell.InlineString = new InlineString(new Text(dc.ColumnName.ToString()));
// consider using cell.CellValue. Then you don't need to use InlineString.
// Because it seems you're not using any rich text so you're just bloating up
// the XML.
r.AppendChild(cell);
ColumnIndexer++;
}
// here's the missing part you needed
sheetdata.Append(r);
RowIndexer = 2;
foreach (DataRow dr in dt.Rows)
{
r = new DocumentFormat.OpenXml.Spreadsheet.Row();
r.RowIndex = (UInt32)RowIndexer;
// this follows the same starting column index as your column header.
// I'm assuming you start with column 1. Change as you see fit.
ColumnIndexer = 1;
foreach (object value in dr.ItemArray)
{
cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
// I moved it here so it's consistent with the above part
// Also, the original code was using the row index to calculate
// the column name, which is weird.
cell.CellReference = ColumnName(ColumnIndexer) + RowIndexer;
cell.DataType = CellValues.InlineString;
cell.InlineString = new InlineString(new Text(value.ToString()));
r.AppendChild(cell);
ColumnIndexer++;
}
RowIndexer++;
// missing part
sheetdata.Append(r);
}
worksheetPart.Worksheet.Save();
wbPart.Workbook.Save();
ssd.Close();
}
Some comments:
The ColumnName() function is from here.
I'm assuming you wanted the column headers in a row, and data in subsequent rows (because the original code had the row index used for calculating the column name).
Cleaned up some parts of the code so it's easier to read and that the column header and data row parts are more consistent in writing style.
I suggest that you consider using CellValue instead of InlineString. Based on your code, you're importing a DataTable, and you don't seem to need rich text so InlineString's are a little overkill and might make the resulting file larger (bloated XML). Use one or the other, and remember to set DataType accordingly.
Also, the code only works for completely empty SheetData.
There are some possible issues here:
You create and add new Rows and Cells: it presumes the worksheet is totally blank when you open it (ie: no rows or cells with the same index/address).
Since you set the CellType to InlineString, you need to set the Cell.InlineString and not Cell.CellValue
cell.DataType = CellValues.InlineString;
cell.InlineString = new InlineString(New Text(value.TsString()));
Also, there is something wrong in your code concerning usage of
CellReference. These parts of code have no sense:
cell.CellReference = dc.ColumnName.ToString();
cell.CellReference = value.ToString();
Cell Address should be something like this "A1". You have to review your code to set the correct address. You already have the rowIndex. You need to get the column name. This Translate a column index into an Excel Column Name can help.

Categories

Resources