Following on from a question about generating Excel files, I need to be able to create the file locally while the webform app is located on the remote web server. This is not anything I've dealt with before, so I am finding it difficult exactly what to ask. I am using WebForms on VS2010 with c#. eanderson pointed me in the direction of Simplexcel by Michael Stum which seems to do the trick but the file is generated on the server (or should I says 'tries to' as it is not permitted!!!).
1 Answer
You should be able to do something similar to this to generate and download the Excel Sheet.
protected void generateExcelSheet_click(object sender, EventArgs e)
{
// Create Excel Sheet
var sheet = new Worksheet("Hello, world!");
sheet.Cells[0, 0] = "Hello,";
sheet.Cells["B1"] = "World!";
var workbook = new Workbook();
workbook.Add(sheet);
// Save
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=MyExcelSheet.xls");
workbook.Save(Response.OutputStream, CompressionLevel.Maximum);
Response.End();
}
In the designer.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="FileDownload.Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:Button ID="btnExcel" runat="server" Text="Download Excel Sheet" onclick="generateExcelSheet_click" />
</form>
</body>
</html>
I based this code on this tutorial.
5 Comments
Peter C
That's great and does the trick, thanks @eanderson. The only question I need to resolve is that when I open the file, I get a message 'The file you are tying to open, "MyExcelSheet.xls", is in a different format than specified by the file extension. Verify that the file is not corrupted and is from a trusted source before opening the file. Do you want to open the file now? If I say yes, the file opens fine. Is this a security issue as I can't see a problem with the file extension?
eandersson
Try changing content-type to
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet or take a look at webmaster-toolkit.com/mime-types.shtml They mention four different content-types you can try.Peter C
Sorry no, that gives the same result.
eandersson
Try to rename the filename to
.xlsx.Peter C
Yes, that did it. Should not be a problem saving as this type. It seems .xls will throw this message as a default (see support.microsoft.com/kb/948615)
var sheet = new Worksheet("Hello, world!"); sheet.Cells[0, 0] = "Hello,"; sheet.Cells["B1"] = "World!"; var workbook = new Workbook(); workbook.Add(sheet); workbook.Save(@"C:\Users\peter\Documents\VS 2010 Projects\ExcelOutput2\www\test.xlsx");