adspace


How to export 2 datatables of a single dataset to 2
different worksheets of a single MSExcel file ?

Answer Posted / Neha Verma

To export two data tables from a single dataset to separate worksheets in an Excel file using C#, you can utilize the Microsoft.Office.Interop.Excel library. First, create and format the workbook and worksheets as needed, then add each data table to its respective worksheet using the 'Range.Value' property. Here's a basic example:

```csharp
using Excel = Microsoft.Office.Interop.Excel;

// Create a new Excel application instance
var excelApp = new Excel.Application();

// Create a new workbook
var workbook = excelApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);

// Get the first worksheet
var worksheet1 = (Excel.Worksheet)workbook.ActiveSheet;
var dataTable1 = ...; // Your first data table
worksheet1.Cells[1, 1].Value2 = "Data Table 1";
worksheet1.Range(worksheet1.Cells[1, 1], worksheet1.Cells[dataTable1.Rows.Count + 1, dataTable1.Columns.Count]).Value2 = dataTable1.AsEnumerable();

// Get the second worksheet
var worksheet2 = (Excel.Worksheet)workbook.Sheets.Add(Missive.msoSheetDefault);
worksheet2.Cells[1, 1].Value2 = "Data Table 2";
worksheet2.Range(worksheet2.Cells[1, 1], worksheet2.Cells[dataTable2.Rows.Count + 1, dataTable2.Columns.Count]).Value2 = dataTable2.AsEnumerable();

// Save the workbook as an Excel file
workbook.SaveAs("path osavefile.xlsx");

// Close the Excel application and release resources
excelApp.Quit();
Marshal.ReleaseComObject(excelApp);
```

Is This Answer Correct ?    0 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

No New Questions to Answer in this Category !!    You can

Post New Questions

Answer Questions in Different Category