Click here to Skip to main content
15,885,944 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Can i save Excel file in my local folder automatically (Without asking any save popup) in c# asp.net ?
Am using below code to create and export excel in my project,
C#
public static void ExportToExcel(DataTable dt, string filename)
      {
          HttpResponse response = HttpContext.Current.Response;
          response.Clear();
          response.Charset = "";
          response.ContentType = "application/download";
          response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + ".xls\"");
          response.ContentEncoding = Encoding.Unicode;
          response.BinaryWrite(Encoding.Unicode.GetPreamble());

          using (StringWriter sw = new StringWriter())
          {
              using (HtmlTextWriter htw = new HtmlTextWriter(sw))
              {
                  DataGrid dg = new DataGrid();
                  dg.DataSource = dt;
                  dg.HeaderStyle.Font.Bold = true;
                  dg.DataBind();
                  foreach (DataGridItem item in dg.Items)
                  {
                      item.Cells[0].Style.Add(HtmlTextWriterStyle.TextAlign, "left");
                  }
                  dg.RenderControl(htw);
                  response.Write(sw.ToString());
                  HttpContext.Current.Response.Flush();
                  HttpContext.Current.Response.SuppressContent = true;
                  HttpContext.Current.ApplicationInstance.CompleteRequest();

              }
          }
      }


This is wroking,but this code will ask for open or save the excel file. I do not want any popup asking save\open. I want code to save this excel in a path given programatically.

How can i do this ?
Posted
Updated 16-Oct-14 21:31pm
v2

Hi Kavitha,

In my opinion, yes you can do this.
Just change your function to this:
C#
public static void ExportToExcel(DataTable dt, string filename)
{
    StreamWriter wr = new StreamWriter(@"D:\\" + filename + ".xls");
    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;
    }

}


And then just call it like this:
C#
ExportToExcel(dt, "FileName");


Hope this works for you !! :) :)

Regards,
Praneet
 
Share this answer
 
Comments
Am Gayathri 17-Oct-14 3:36am    
Hi Praneeth,
Great Thanks a lot...

One more doubt
can i put line break in cell vale ?
Ie if tha value is like abc<br/>def then a line break should come after abc is that possible ?
My datatable contins values like abc<br/>def ...
[no name] 17-Oct-14 3:42am    
Hi,

In that case you will have to check while writing to the cell value and write your own login based on your DataTable.
You can then add "\n" or Environment.NewLine in between to work it as break.

Regards,
Praneet
Am Gayathri 17-Oct-14 5:55am    
Its going to next cell line. :(
I want it in same cell with next line like wrap text.
Hi,

For formatting you will have to create a workbook using interop.

Like this:

1.) Create a sample dt, with new row/ break for a column:
C#
System.Data.DataTable dt = new System.Data.DataTable();
            DataSet ds = new DataSet();
            dt.TableName = "tablename";
            dt.Columns.Add("Code", typeof(string));
            dt.Columns.Add("Price", typeof(int));

            DataRow dr = dt.NewRow();
            dr["Code"] = "ABC " + Environment.NewLine + " qrt";
            dr["Price"] = 12;

            dt.Rows.Add(dr);

            DataRow dr1 = dt.NewRow();
            dr1["Code"] = "PQR";
            dr1["Price"] = 1;

            dt.Rows.Add(dr1);


2.) Create the workbook function using Interop.
C#
public static void CreateWorkbook(System.Data.DataTable dt, String path)
    {
        int rowindex = 0;
        int columnindex = 0;

        Microsoft.Office.Interop.Excel.Application wapp = new Microsoft.Office.Interop.Excel.Application();
        Microsoft.Office.Interop.Excel.Worksheet wsheet;
        Microsoft.Office.Interop.Excel.Workbook wbook;

        wapp.Visible = false;

        wbook = wapp.Workbooks.Add(true);
        wsheet = (Worksheet)wbook.ActiveSheet;


        try
        {
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                wsheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;

            }

            foreach (DataRow row in dt.Rows)
            {
                rowindex++;
                columnindex = 0;
                foreach (DataColumn col in dt.Columns)
                {
                    columnindex++;
                    wsheet.Cells[rowindex + 1, columnindex] = row[col.ColumnName];
                }
            }
        }
        catch (Exception ex)
        {
            String err = ex.Message;
        }
        wapp.UserControl = true;

        wbook.SaveAs("d:\\Test", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing,
        false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
        Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
        wbook.Close(null,null,null);


3.) To save the file, call the function like this:
C#
CreateWorkbook(dt,"D:/");


You can apply many formatting types to cells, as per your requirement.
Also, this will save automatically, without user prompt.

Regards,
Praneet
 
Share this answer
 
v2
Comments
Am Gayathri 17-Oct-14 7:16am    
Thanks Praneet
Am Gayathri 19-Oct-14 9:49am    
Hi Praneet,

This works in local but when run this in my server below error is coming

System.Runtime.InteropServices.COMException (0x80040154): Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).

See the question

http://www.codeproject.com/Questions/831023/Getting-error-while-creating-excel-in-server?arn=0

please help

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900