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

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

Related

Excel with multiple Sheets causing issues with Open Xml

I tried to create an excel with multiple sheets and different data count in both sheets. but when i tried to create only one row was getting added in both sheets and not more than that and when i open the excel it asks for repair.
`
MemoryStream ms = new MemoryStream();
SpreadsheetDocument xl = SpreadsheetDocument.Create(ms, SpreadsheetDocumentType.Workbook);
byte[] dt = null;
// Add a WorkbookPart to the document
WorkbookPart workbookPart = xl.AddWorkbookPart();
workbookPart.Workbook = new Workbook();
tracing.Trace("Temp Plugin Executed");
Sheets sheets = xl.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());
// Begin: Code block for Excel sheet 1
WorksheetPart worksheetPart1 = workbookPart.AddNewPart<WorksheetPart>();
Worksheet workSheet1 = new Worksheet();
SheetData sheetData1 = new SheetData();
// the data for sheet 1
Row rowInSheet1 = new Row();
Cell emptyCell = CreateTextCell("A", "111", 1);
rowInSheet1.Append(emptyCell);
sheetData1.Append(rowInSheet1);
workSheet1.Append(sheetData1);
worksheetPart1.Worksheet = workSheet1;
Sheet sheet1 = new Sheet()
{
Id = xl.WorkbookPart.GetIdOfPart(worksheetPart1),
SheetId = 1,
Name = "Sheet1"
};
sheets.Append(sheet1);
// End: Code block for Excel sheet 1
// Begin: Code block for Excel sheet 2
WorksheetPart worksheetPart2 = workbookPart.AddNewPart<WorksheetPart>();
Worksheet workSheet2 = new Worksheet();
SheetData sheetData2 = new SheetData();
// the data for sheet 2
Row rowInSheet2 = new Row();
Cell mycell = CreateTextCell("A", "data", 1);
Cell mycell1 = CreateTextCell("A", "data", 2);
rowInSheet2.Append(mycell);
rowInSheet2.Append(mycell1);
sheetData2.Append(rowInSheet2);
workSheet2.Append(sheetData2);
worksheetPart2.Worksheet = workSheet2;
Sheet sheet2 = new Sheet()
{
Id = xl.WorkbookPart.GetIdOfPart(worksheetPart2),
SheetId = 2,
Name = "Sheet2"
};
sheets.Append(sheet2);
xl.Close();
dt = ms.ToArray();
public Cell CreateTextCell(string header, string text, int index)
{
//Create a new inline string cell.
Cell c = new Cell();
c.DataType = CellValues.InlineString;
c.CellReference = header + index;
//Add text to the text cell.
InlineString inlineString = new InlineString();
Text t = new Text();
t.Text = text;
inlineString.AppendChild(t);
c.AppendChild(inlineString);
return c;
}
`
I tried creating multiple sheets with different data count on both sheets
The second cell should be B1 not A2. It's the second cell in the first row. That's how Excel works. So the code should look like:
Cell mycell = CreateTextCell("A", "data", 1);
Cell mycell1 = CreateTextCell("B", "data2", 1);
To add a second row on the second worksheet:
// the data for sheet 2
Row row2InSheet2 = new Row() { RowIndex = 2 };
sheetData2.Append(row2InSheet2);
// In the new row, find the column location to insert a cell in A2.
Cell refCell = null;
foreach (Cell cell in row2InSheet2.Elements<Cell>())
{
if (string.Compare(cell.CellReference.Value, "A2", true) > 0)
{
refCell = cell;
break;
}
}
Cell mycellRow21 = CreateTextCell("A", "new_row_test1", 2);
row2InSheet2.InsertBefore(mycellRow21, refCell);
You can study the Microsoft documentation on OpenXml for more examples

C# OpenXML Changing Column Background

I have a code left by the previous developer. What I need to do is to change the background color and text color of the header columns in the Excel file. But I just couldn't. We use OpenXML. Heading columns are added as rows. I can't change background and text color of these header row. How can I change the background color of the cell interiors in the cell variable?
public byte[] analizVerileriExport(DataTable data)
{
byte[] result;
using (MemoryStream mem = new MemoryStream())
{
using (var spreadsheetDocument = SpreadsheetDocument.Create(mem, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
{
// Add a WorkbookPart to the document.
WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
// Add a WorksheetPart to the WorkbookPart.
WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
SheetData sheetData = new SheetData();
worksheetPart.Worksheet = new Worksheet(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 = string.IsNullOrEmpty(data.TableName) ? "Analiz Verileri" : data.TableName
};
Row headerRow = new Row();
List<excelColumns> columns = new List<excelColumns>();
foreach (DataColumn column in data.Columns)
{
columns.Add(new excelColumns() { columnName = column.ColumnName, columnDataType = column.DataType });
Cell cell = new Cell();
cell.DataType = CellValues.String;
cell.CellValue = new CellValue(column.ColumnName);
headerRow.AppendChild(cell);
}
sheetData.AppendChild(headerRow);
foreach (DataRow dsrow in data.Rows)
{
Row newRow = new Row();
foreach (excelColumns col in columns)
{
Cell cell = new Cell();
cell.DataType = col.columnDataType.ToCellValue();
cell.CellValue = new CellValue(dsrow[col.columnName].ToString()); //
newRow.AppendChild(cell);
}
sheetData.AppendChild(newRow);
}
sheets.Append(sheet);
workbookpart.Workbook.Save();
// Close the document.
spreadsheetDocument.Close();
}
result = mem.ToArray();
}
//string excelName = cmbClient.Text + " Kişisel Veri Envanteri " + String.Format("{0:dd_MM_yyyy HH-mm-ss}", DateTime.Now) + ".xlsx";
//openFile(excelName, result);
return result;
}

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 to create Table inside Excel Sheet?

Use DocumentFormat.Openxml 2.8.1.
I try to create Excel Sheet and create Table inside it.
But when i do it - and try to open excel file - excel says that can not open and try to restore this file.
So, i create excel file:
var fStream = new FileStream(tempPathName, FileMode.Open, FileAccess.ReadWrite, FileShare.None, 1048, FileOptions.DeleteOnClose);
SpreadsheetDocument ssDoc = SpreadsheetDocument.Create(inputStream,
SpreadsheetDocumentType.Workbook);
Then , create sheet:
var tempPathName = Path.GetTempFileName();
WorkbookPart workbookPart = ssDoc.AddWorkbookPart();
workbookPart.Workbook = new Workbook();
Sheets sheets = ssDoc.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());
WorksheetPart worksheetPart4 = workbookPart.AddNewPart<WorksheetPart>();
worksheetPart4.Worksheet = new Worksheet();
Worksheet workSheet4 = worksheetPart4.Worksheet;
var table = CreateTable1();
TableParts tableParts = new TableParts() { Count = (UInt32)1 };
TablePart tablePart = new TablePart() { Id = "rId" + 1 };
tableParts.Append(table);
tableParts.Append(tablePart);
workSheet4.AppendChild(tableParts);
Sheet sheet4 = new Sheet()
{
Id = ssDoc.WorkbookPart.GetIdOfPart(worksheetPart4),
SheetId = 4,
Name = "test"
};
sheets.Append(sheet4);
ssDoc.Close();
private Table CreateTable1()
{
// First, we create the table, its properties and we append it.
Table table = new Table();
TableProperties props = new TableProperties();
table.AppendChild<TableProperties>(props);
// Now we create a new layout and make it "fixed".
TableLayout tl = new TableLayout() { Type = TableLayoutValues.Fixed };
props.TableLayout = tl;
// Then we just create a new row and a few cells and we give them a width
var tr = new TableRow();
var tc1 = new TableCell();
var tc2 = new TableCell();
tc1.Append(new TableCellProperties(new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2000" }));
tc2.Append(new TableCellProperties(new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2000" }));
table.Append(tr);
return table;
}
So, how to create table in Excel sheet and insert data in table?
Thank you.
TableStyle class is what you`re looking for.
You actually have to create TableStyle and add it to your spreadsheet.
In CreateTable1(), TableProperties, TableLayout, TableRow, and TableCell are WordProcessing elements.
Instead, you will want to use code similar to this:
private void CreateTable2(SheetData sheetData)
{
var row1 = new Row(){ RowIndex = 1 };
sheetData.Append(row1);
var cell1 = new Cell();
cell1.DataType = CellValues.InlineString;
cell1.InlineString = new InlineString() { Text = new Text("Hello") };
row1.InsertAt(cell1, 0);
var cell2 = new Cell();
cell2.DataType = CellValues.InlineString;
cell2.InlineString = new InlineString() { Text = new Text("World") };
row1.InsertAt(cell2, 1);
}
Slightly modify the rest of your code to look like the following (most of which I borrowed from here).
var fStream = new FileStream(tempPathName, FileMode.Create);
SpreadsheetDocument ssDoc = SpreadsheetDocument.Create(fStream, SpreadsheetDocumentType.Workbook);
// Add a WorkbookPart to the document.
WorkbookPart workbookPart = ssDoc.AddWorkbookPart();
workbookPart.Workbook = new Workbook();
// Add a WorksheetPart to the WorkbookPart.
WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
// Add Sheets to the Workbook.
Sheets sheets = ssDoc.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());
// Append a new worksheet and associate it with the workbook.
Sheet sheet = new Sheet()
{
Id = ssDoc.WorkbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "mySheet"
};
sheets.Append(sheet);
// Get the sheetData cell table.
SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();
CreateTable2(sheetData);
workbookPart.Workbook.Save();
ssDoc.Close();
fStream.Close();

How can we insert the next row of the excel sheet if the current excel sheet having the records?

How can we able to write next row of the excel sheet if it ave records during exporting data from c#
it is the code i used for exporting data. to excel . i failed to export the data to next line by this code
private void ExportToOxml(bool firstTime)
{
if (count == 0)
{
ResultsData.Columns.Remove("TotalRecords");
ResultsData.Columns.Remove("PageIndex");
// fileName = #"C:\MyExcel.csv";
//Delete the file if it exists.
if (firstTime && File.Exists(xsfd.FileName))
{
File.Delete(fileName);
}
count++;
}
if (firstTime)
{
//This is the first time of creating the excel file and the first sheet.
// Create a spreadsheet document by supplying the filepath.
// By default, AutoSave = true, Editable = true, and Type = xlsx.
SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.
Create(fileName, SpreadsheetDocumentType.Workbook);
// Add a WorkbookPart to the document.
WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
// Add a WorksheetPart to the WorkbookPart.
var worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
var sheetData = new SheetData();
worksheetPart.Worksheet = new Worksheet(sheetData);
var bold1 = new System.Windows.Documents.Bold();
CellFormat cf = new CellFormat();
// Add Sheets to the Workbook.
Sheets sheets;
sheets = spreadsheetDocument.WorkbookPart.Workbook.
AppendChild<Sheets>(new Sheets());
// Append a new worksheet and associate it with the workbook.
var sheet = new Sheet()
{
Id = spreadsheetDocument.WorkbookPart.
GetIdOfPart(worksheetPart),
SheetId = sheetId,
Name = "Sheet" + sheetId
};
sheets.Append(sheet);
//Add Header Row.
var headerRow = new Row();
foreach (DataColumn column in ResultsData.Columns)
{
var cell = new Cell { DataType = CellValues.String, CellValue = new CellValue(column.ColumnName) };
headerRow.AppendChild(cell);
}
sheetData.AppendChild(headerRow);
foreach (DataRow row in ResultsData.Rows)
{
var newRow = new Row();
foreach (DataColumn col in ResultsData.Columns)
{
var cell = new Cell
{
DataType = CellValues.String,
CellValue = new CellValue(row[col].ToString())
};
newRow.AppendChild(cell);
}
sheetData.AppendChild(newRow);
}
workbookpart.Workbook.Save();
spreadsheetDocument.Close();
}
else
{
// Open the Excel file that we created before, and start to add sheets to it.
var spreadsheetDocument = SpreadsheetDocument.Open(fileName, true);
var workbookpart = spreadsheetDocument.WorkbookPart;
if (workbookpart.Workbook == null)
workbookpart.Workbook = new Workbook();
var worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
var sheetData = new SheetData();
worksheetPart.Worksheet = new Worksheet(sheetData);
var sheets = spreadsheetDocument.WorkbookPart.Workbook.Sheets;
if (sheets.Elements<Sheet>().Any())
{
//Set the new sheet id
sheetId = sheets.Elements<Sheet>().Max(s => s.SheetId.Value) + 1;
}
else
{
sheetId = 1;
}
// Append a new worksheet and associate it with the workbook.
var sheet = new Sheet()
{
Id = spreadsheetDocument.WorkbookPart.
GetIdOfPart(worksheetPart),
SheetId = sheetId,
Name = "Sheet" + sheetId
};
sheets.Append(sheet);
//Add the header row here.
var headerRow = new Row();
foreach (DataColumn column in ResultsData.Columns)
{
var cell = new Cell { DataType = CellValues.String, CellValue = new CellValue(column.ColumnName) };
headerRow.AppendChild(cell);
}
sheetData.AppendChild(headerRow);
foreach (DataRow row in ResultsData.Rows)
{
var newRow = new Row();
foreach (DataColumn col in ResultsData.Columns)
{
var cell = new Cell
{
DataType = CellValues.String,
CellValue = new CellValue(row[col].ToString())
};
newRow.AppendChild(cell);
}
sheetData.AppendChild(newRow);
}
workbookpart.Workbook.Save();
// Close the document.
spreadsheetDocument.Close();
}
}

Categories

Resources