Kevin S
Kevin S

Reputation: 33

C# console application save excel file (do not prompt)

I want to write a console application where I will pull data into a dataset. I then want to save the file to a local hard drive. I have the code in my webapp which prompts the user to save it, but I would like to save it to local hard drive of the server and send email to user. Here is my code so far:

Response.Clear();
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=Test.xls;");
Response.Charset = "";

System.IO.StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
dg.RenderControl(htw);
Response.Write("<style>.fraction { mso-number-format:#\\/#; }</style>");                   
Response.Write(sw.ToString());

Response.End();

I would appreciate any help. Thanks.

Upvotes: 0

Views: 5821

Answers (2)

GrayFox374
GrayFox374

Reputation: 1782

This is a snippet from a console app of mine, it saves a file without a prompt from the user. You must add a COM reference for Excel.

    private void btnExcel_Click(object sender, EventArgs e)
    {
        Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
        app.Visible = true;
        Microsoft.Office.Interop.Excel.Workbook wb = app.Workbooks.Add(1);
        Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets[1];
        int i = 1;
        int i2 = 1;
        foreach (ListViewItem lvi in lvwResults.Items)
        {
            i = 1;
            foreach (ListViewItem.ListViewSubItem lvs in lvi.SubItems)
            {
                ws.Cells[i2, i] = lvs.Text;
                i++;
            }
            i2++;
        }

        wb.SaveAs(String.Format(@"C:\MyReportABC-{0}-{1}", String.Format("{0:yyyyMMdd}", DateTime.Today), String.Format("{0:hhmm}", DateTime.Now)));
        wb.Close(true);
    }

Outputs a file named MyReportABC-20120621-0539.xls (changes on everytime, you could add a user ID in the string as well)

Upvotes: 0

Michael Edenfield
Michael Edenfield

Reputation: 28338

The user is being prompted to save the file by the browser, not by your web app. If you have a locally executing console application, you can bypass all of that and simply open a FileStream for writing, and associate your HtmlTextWriter with that. It would only prompt the user to overwrite if you explicitly wrote the code to do that.

Upvotes: 1

Related Questions