How to Append data coloms in a worksheet from a data table in Excel Interop c#

RAMAN RAGAVAN 51 Reputation points
2022-02-02T18:35:19.953+00:00

I have 3 tables having almost same data and same data colom.I need to expoert this 3 table together to one excel sheet side by side. i have 3 datatable ,each dt have 2 cloms so my excel should have 2+2+2= 6 coloms.How can i add like this? below is my methods.where i have to change? please help

    public static void CreateExcelSheet(DataSet result, string excelPath)

    {
 var ds= new DataSet();

DataTable dt1 = new DataTable();

dt1.Columns.Add("Name", typeof(string));

dt1.Columns.Add("Age", typeof(int));

// Create a DataRow, add Name and Age data, and add to the DataTable

DataRow dr1 = dt1.NewRow();

dr1["Name"] = "Mohammadsd"; // or dr[0]="Mohammad";

dr1["Age"] = 24; // or dr[1]=24;

dt1.Rows.Add(dr1);

result.Tables.Add(dt1);



DataTable dt2 = new DataTable();

dt2.Columns.Add("Name", typeof(string));

dt2.Columns.Add("Age", typeof(int));

// Create a DataRow, add Name and Age data, and add to the DataTable

DataRow dr2 = dt2.NewRow();

dr2["Name"] = "Mohammad"; // or dr[0]="Mohammad";

dr2["Age"] = 24; // or dr[1]=24;

dt2.Rows.Add(dr2);

result.Tables.Add(dt2);



DataTable dt3 = new DataTable();

dt3.Columns.Add("Name", typeof(string));

dt3.Columns.Add("sex", typeof(int));

// Create a DataRow, add Name and Age data, and add to the DataTable

DataRow dr3 = dt3.NewRow();

dr3["Name"] = "last"; // or dr[0]="Mohammad";

dr3["sex"] = 24; // or dr[1]=24;

dt3.Rows.Add(dr3);

ds.Tables.Add(dt3);






        object misValue = System.Reflection.Missing.Value;

        Excel.Application xlApp = new Excel.Application();

        Excel.Workbook xlWorkBook = xlApp.Workbooks.Add(misValue);



        for (int i = 0; i < ds.Tables.Count; i++)

        {

            DataTable table = ds.Tables[i];

            Excel._Worksheet xlWorkSheet = xlWorkBook.Sheets.Count <= i

                ? (Excel._Worksheet)xlWorkBook.Sheets.Add(After: xlWorkBook.Sheets[xlWorkBook.Sheets.Count])

                : (Excel._Worksheet)xlWorkBook.Sheets[ 1]; //same sheet


            xlWorkSheet.Columns.NumberFormat = "@";

            AddDataToWorksheet(xlWorkSheet, table);

            xlWorkSheet.Columns.AutoFit();

            xlWorkSheet.Rows.AutoFit();

            Marshal.ReleaseComObject(xlWorkSheet);

        }

        xlWorkBook.SaveAs(excelPath);

        xlWorkBook.Close();

        xlApp.Quit();

        Marshal.ReleaseComObject(xlWorkBook);

        Marshal.ReleaseComObject(xlApp);

    }



 private static void AddDataToWorksheet(Excel._Worksheet sheet, DataTable table)

    {

        sheet.Name = "Report";

        for (int i = 0; i < table.Columns.Count; i++)

        {

            sheet.Cells[1, i + 1] = table.Columns[i].ColumnName;

        }

        for (int i = 0; i < table.Rows.Count; i++)

        {

            int rowNumber = i + 2;

            DataRow row = table.Rows[i];

            for (int j = 0; j < table.Columns.Count; j++)

            {

                sheet.Cells[rowNumber, j + 1] = Convert.ToString(row[j]);

            }

        }

    }
Developer technologies | C#
{count} votes

1 answer

Sort by: Most helpful
  1. Jack J Jun 25,296 Reputation points
    2022-02-10T08:55:53.217+00:00

    @RAMAN RAGAVAN , Welcome to Microsoft Q&A, Based on my further test, you could try to use the following code to append data coloms in a worksheet from dataset.

    static void Main(string[] args)  
            {  
               DataSet ds = GetDataSet();  
               string excelfile = @"t1.xlsx";  
                for (int i = 0; i < ds.Tables.Count; i++)  
                {  
                    ExportToExcel(ds.Tables[i], excelfile);  
                }  
                 
      
      
            }  
            public static void ExportToExcel(DataTable tbl, string excelFilePath = null)  
            {  
                var excelApp = new Excel.Application();  
                try  
                {  
                  
                    if (!File.Exists(excelFilePath))  
                    {  
                          
                        excelApp.Workbooks.Add();  
      
                        // single worksheet  
                        Excel._Worksheet workSheet = excelApp.ActiveSheet;  
      
                        // column headings  
                        for (var i = 0; i < tbl.Columns.Count; i++)  
                        {  
                            workSheet.Cells[1, i + 1] = tbl.Columns[i].ColumnName;  
                        }  
      
                        // rows  
                        for (var i = 0; i < tbl.Rows.Count; i++)  
                        {  
                            // to do: format datetime values before printing  
                            for (var j = 0; j < tbl.Columns.Count; j++)  
                            {  
                                workSheet.Cells[i + 2, j + 1] = tbl.Rows[i][j];  
                            }  
                        }  
                        workSheet.SaveAs(excelFilePath);  
                    }  
                    else  
                    {  
                          
                        var workbook = excelApp.Workbooks.Open(excelFilePath);  
                        Excel._Worksheet workSheet = workbook.Sheets[1];  
                        var row = workSheet.UsedRange.Rows.Count;  
                        var col= workSheet.UsedRange.Columns.Count;  
                        for (var i = 0; i < tbl.Columns.Count; i++)  
                        {  
                            workSheet.Cells[1, i + 1+col] = tbl.Columns[i].ColumnName;  
                        }  
      
                        // rows  
                        for (var i = 0; i < tbl.Rows.Count; i++)  
                        {  
                            // to do: format datetime values before printing  
                            for (var j = 0; j < tbl.Columns.Count; j++)  
                            {  
                                workSheet.Cells[i + 2, j + 1+col] = tbl.Rows[i][j];  
                            }  
                        }  
                        workbook.Save();  
      
                    }  
      
                    // load excel, and create a new workbook  
                    
                }  
                catch (Exception ex)  
                {  
                    throw new Exception("ExportToExcel: \n" + ex.Message);  
                }  
                finally  
                {  
                    excelApp.Quit();  
                }  
            }  
            static DataSet GetDataSet()  
            {  
                var ds = new DataSet();  
                DataTable dt1 = new DataTable();  
                dt1.Columns.Add("Name", typeof(string));  
                dt1.Columns.Add("Age", typeof(int));  
                // Create a DataRow, add Name and Age data, and add to the DataTable  
                DataRow dr1 = dt1.NewRow();  
                dr1["Name"] = "Mohammadsd"; // or dr[0]="Mohammad";  
                dr1["Age"] = 24; // or dr[1]=24;  
                dt1.Rows.Add(dr1);  
                ds.Tables.Add(dt1);  
                DataTable dt2 = new DataTable();  
                dt2.Columns.Add("Name", typeof(string));  
                dt2.Columns.Add("Age", typeof(int));  
      
                // Create a DataRow, add Name and Age data, and add to the DataTable  
                DataRow dr2 = dt2.NewRow();  
                dr2["Name"] = "Mohammad"; // or dr[0]="Mohammad";  
                dr2["Age"] = 24; // or dr[1]=24;  
                dt2.Rows.Add(dr2);  
                dt2.Rows.Add("test2", 26);  
                ds.Tables.Add(dt2);  
                DataTable dt3 = new DataTable();  
                dt3.Columns.Add("Name", typeof(string));  
                dt3.Columns.Add("sex", typeof(int));  
                // Create a DataRow, add Name and Age data, and add to the DataTable  
                DataRow dr3 = dt3.NewRow();  
                dr3["Name"] = "last"; // or dr[0]="Mohammad";  
                dr3["sex"] = 24; // or dr[1]=24;  
                dt3.Rows.Add(dr3);  
                  
                ds.Tables.Add(dt3);  
                return ds;  
            }  
    

    Result:
    173122-image.png

    Best Regards,
    Jack


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.