C# Open XML SDK 2.0 Excel spreadsheet – load range of cells from string array

cexcelinsertopenxmlrows

In a .Net windows desktop application, I am able to import a string array of data into a range of cells located in Excel spreadsheet. The C# code is as follows:

using Excel = Microsoft.Office.Interop.Excel;

// Create Application, Workbook, and Worksheet
xlApp = new Microsoft.Office.Interop.Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWs = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

// Move data from temp array into Excel spreadsheet.
Excel.Range c1 = (Excel.Range)xlWs.Cells[startRowNum, 1];
Excel.Range c2 = (Excel.Range)xlWs.Cells[startRowNum + myTable.Rows.Count - 1,   Columns.Count];
Excel.Range range = xlWs.get_Range(c1, c2);
range.Value = tempArray;

I am trying to duplicate this process in an ASP.Net webpage. Using Visual Studio 2010 and C#. How can I do this same import of a string array into an Open XML SDK 2.0 Excel spreadsheet range of cells?

Best Answer

As answered, a library might be easier to use. An alternative library choice is SpreadsheetLight. Here's how the code might look like:

SLDocument sl = new SLDocument("YourFile.xlsx");
// row 1 column 1
sl.SetCellValue(1, 1, "String1");
// row 1 column 2
sl.SetCellValue(1, 2, "String2");
sl.SaveAs("AnotherFile.xlsx");

You don't have to worry about which order you set the cell values. Internally, SpreadsheetLight runs on Open XML SDK. Disclaimer: I wrote SpreadsheetLight.

Related Topic