Search code examples
c#exceldatatableoledb

exporting data set to excelsheet


I am new to excel automation in C# so I am confused about this. I have imported an excel in a dataset and I have done some updates in the dataset as per my requirement. now I want to export that dataset to that input sheet so that I can see the updates done in the dataset reflected in the datasheet. what will be the best approach for exporting dataset to excel. below is the code of how I am opening the excel sheet:

string sConnection = null;
OleDbConnection oleExcelConnection = default(OleDbConnection);
sConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\input.xls;Extended Properties=\"Excel 12.0;HDR=No;IMEX=1\"";
oleExcelConnection = new OleDbConnection(sConnection);
oleExcelConnection.Open();

string sqlquery = "Select * From [c:\input.xls]";
DataSet ds = new DataSet();
OleDbDataAdapter da = new OleDbDataAdapter(sqlquery, oleExcelConnection);
da.Fill(ds);
System.Data.DataTable dt = ds.Tables[0];

/* 10 to 12 linq queries on dt*/

-> now here I want to export the updated dt to input.xls

Solution

  • after research of many hours, I found a way to write an excel using datatable. Although, my original requirement was to update the original sheet, I guess I will have to be happy with creating a new output sheet from scratch. the solution is given below:

    //open file
    StreamWriter wr = new StreamWriter(@"D:\\Book1.xls");
    // dt is the DataTable needed to be dumped in an excel sheet.
    try
    {
    
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            wr.Write(dt.Columns[i].ToString().ToUpper() + "\t");
        }
    
        wr.WriteLine();
    
        //write rows to excel file
        for (int i = 0; i < (dt.Rows.Count); i++)
        {
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                if (dt.Rows[i][j] != null)
                {
                    wr.Write(Convert.ToString(dt.Rows[i][j]) + "\t");
                }
                else
                {
                    wr.Write("\t");
                }
            }
            //go to next line
            wr.WriteLine();
        }
        //close file
        wr.Close();
    }
    catch (Exception ex)
    {
        throw ex;
    }