Export DataSet into Excel using C# Excel Interop
کد:
using System.Data;
using Excel = Microsoft.Office.Interop.Excel;
namespace ExportDataSetToExcel
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
DataTable employeeTable = new DataTable("Employee");
employeeTable.Columns.Add("Employee ID");
employeeTable.Columns.Add("Employee Name");
employeeTable.Rows.Add("1", "ABC");
employeeTable.Rows.Add("2", "DEF");
employeeTable.Rows.Add("3", "PQR");
employeeTable.Rows.Add("4", "XYZ");
// ساختن جدول از نوع datatable
DataTable departmentTable = new DataTable("Department");
departmentTable.Columns.Add("Department ID");
departmentTable.Columns.Add("Department Name");
departmentTable.Rows.Add("1", "IT");
departmentTable.Rows.Add("2", "HR");
departmentTable.Rows.Add("3", "Finance");
DataSet ds = new DataSet("Organization");
ds.Tables.Add(employeeTable);
ds.Tables.Add(departmentTable);
p.ExportDataSetToExcel(ds);
}
private void ExportDataSetToExcel(DataSet ds)
{
Excel.Application excelApp = new Excel.Application();
Excel.Workbook excelWorkBook = excelApp.Workbooks.Open(@"E:\Org.xlsx");
foreach (DataTable table in ds.Tables)
{
Excel.Worksheet excelWorkSheet = excelWorkBook.Sheets.Add();
excelWorkSheet.Name = table.TableName;
for (int i = 1; i < table.Columns.Count + 1; i++)
{
excelWorkSheet.Cells[1, i] = table.Columns[i - 1].ColumnName;
}
for (int j = 0; j < table.Rows.Count; j++)
{