 |
|
 |
Ok so it doesn't have all the whistles and bells of some solutions but for getting basic data into an Excel sheet this works great. After playing around with various more complex solutions this does everything I want.
Sometimes it's easy to overlook the obvious!
|
|
|
|
 |
|
 |
When some special characters like 'ü' are exported from grid, then that character is displayed as some other special character 'ü'
|
|
|
|
 |
|
 |
This doesn't export to Excel format (XLS, XLSX), it just exports to HTML that Microsoft Excel interprets right, although you assigned .xls file extension.
To me this is just wrong. It would be much better to export it as a CSV file, if you don't need any formatting.
If you need to export DataTable to real Excel format (XLS, XLSX), I recommend this Excel C# / VB.NET library.
It doesn't use Excel automation and is very fast.
Here is an Excel C# sample how to export DataTable to Excel:
var ef = new ExcelFile();
ef.Worksheets.Add(dataTable.TableName).InsertDataTable(dataTable, 0, 0, true);
ef.SaveXls(dataTable.TableName + ".xls");
|
|
|
|
 |
|
 |
public void dtToCsv(DataTable dt)
{
StreamWriter sw = new StreamWriter(@"C:\Temp\" + @"sample" + ".csv", true); //Open new file
try
{
int colCount = dt.Columns.Count; //Total number of Columns
for (int c = 0; c < colCount; c++) //Write different column names with ','
{
sw.Write(dt.Columns[c]);
if (c < colCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
foreach (DataRow dr in dt.Rows)
{
for (int r = 0; r < colCount; r++)
{
if (!Convert.IsDBNull(dr[r]))
{
if (dr[r].GetType().ToString() == "System.String") //Will check column is string or not
{
sw.Write(dr[r].ToString());
}
else
{
sw.Write(dr[r].ToString());
}
}
if (r < colCount - 1)
{
sw.Write(",");
}
}
sw.WriteLine();
}
sw.WriteLine(sw.NewLine);
sw.Write("File Compiled at " + System.DateTime.Now);
}
finally
{
sw.Close();
}
}
|
|
|
|
 |
|
 |
This is really quick way of generating the excel format. Other approaches take lot of time. This approach helped in getting the excel export in just 10mins. Thats great saving. Thanks for sharing this.
|
|
|
|
 |
|
 |
A really great simple solution.
|
|
|
|
 |
|
|
 |
|
 |
This method of exporting is really awesome
meanwhile I have one question how to keep apply formating for excel , I means the date time is exporting as time part 00:00 or if any column as currency then how to apply currency formate
Regards
Sac
|
|
|
|
 |
|
 |
I'ved worked with several methods to export tables to excel and all of them suck! Plus most of them have bad memory management and are more slow. This is just Great for a simple task. Thanks a lot!
Ariel
|
|
|
|
 |
|
 |
Clever use of existing stuff.
The people crying about this article should take a deep breath and consider that sometimes you just need to dump a simple table to xls. And given that the final product is in fact a table dumped to xls, I'm gonna' have to go ahead and say it works just fine.
--
Saving the world, one line of code at a time
|
|
|
|
 |
|
|
 |
|
 |
Great ideal. Thanks!
Something should remember but some thing should forget. Your life will brighter
|
|
|
|
 |
|
 |
I implemented this way in an ASP.NET (here they does VB, I don't) application I'm developing. IT is working correctly, however the path is kinda burnt in code. I try using a fileUpload control to allow the user to chose a location, and it did not work. I also try using some environment variables but they are server related, so I can not access a path in the client machine.
How it is possible to make it work as a download process?
thanks a lot.
btw many ppl uses this or other similar ways to export to excel. since you don't need fancy files and you don't have lot of time it works just fine with datatables of more than 3000 rows. So I have to thank you.
Frank Silva
|
|
|
|
 |
|
 |
This code runs only on the server, so offering a file download has two parts:
1. Someone clicks the "download" link or button on your page, and in the handler for that you run the code to create the excel file and temporarily stash it somewhere on the SERVER (as you saw, you can use variables to set the file path).
2. As with any other file download, you can redirect the Response to this file you just created (if it's in a web-accessible location), or just write the binary file to the Response with appropriate MIME info. When the client's web browser sees a file coming back it will let the user select a place to save it on his own computer.
|
|
|
|
 |
|
 |
You are the man...
Regards,
Farrukh Malik
+92-300-2564099
|
|
|
|
 |
|
 |
This article helped me a lot, but then I found that my input spreadsheet (717 rows, 7 columns) lost some rows when I saved it after adding 6 columns to it. The solution was to flush and close the streamwriter. That gave me the entire output spreadsheet. (My apologies to the C# folk, but I work in VB.NET.)
Dim grid As System.Web.UI.WebControls.DataGrid
grid = New System.Web.UI.WebControls.DataGrid
grid.DataSource = objDataset2
grid.DataMember = objDataset2.Tables(0).TableName
grid.DataBind()
Dim sw As StreamWriter
sw = New StreamWriter(savNewSpreadsheetDialog.FileName)
Dim hw As HtmlTextWriter
hw = New HtmlTextWriter(sw)
grid.RenderControl(hw)
sw.Flush()
sw.Close()
|
|
|
|
 |
|
 |
Excellent point! I will add that info if/when I update the article.
For those using C#, if you utilize the "using" blocks as in the example, manually flushing the streamwriter is not necessary since the runtime will automatically handle that when exiting the using block.
|
|
|
|
 |
|
 |
Does anyone know if this works with Excel 2000? I'm searching for a export to excel solution supported by Excel 2000+. XML Spreadsheet format is only supported by Excel 2002/2003+ I believe, and I want to refrain from csv just because I need to export multiple tables (ideally a workbook with multiple sheets) and having some formatting would be nice. Thanks!
|
|
|
|
 |
|
 |
I don't have office 2000 handy but according to one site "Excel 97+ can import (and export) an HTML table" (http://www.dpawson.co.uk/xsl/sect4/spreadsheet.html)
Other sites seem to concur.
Also, I kinda doubt it's possible to create a workbook w/ multiple sheets using this method, but I could be wrong! You might try creating a multisheet excel doc and exporting it to HTML, then take a look at what it spits out. You might be able to parse the proper format from there.
|
|
|
|
 |
|
 |
Hi- Thanks for your reply. I found online this bit of code that will create a second worksheet but then couldn't figure out how to actually write to this second sheet: <html xmlns ="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"> <head> <meta http-equiv=Content-Type content="text/html; charset=windows-1252"> <meta name=ProgId content=Excel.Sheet> <meta name=Generator content="Microsoft Excel 9"> </head> <body link=blue vlink=purple> <!-- Creation of 2 worksheets - data1 and data2 --> <xml> <x:ExcelWorkbook> <x:ExcelWorksheets> <x:ExcelWorksheet> <x:Name>data1</x:Name> <x:WorksheetOptions> <x:Selected/> <x:ProtectContents>False</x:ProtectContents> <x:ProtectObjects>False</x:ProtectObjects> <x:ProtectScenarios>False</x:ProtectScenarios> </x:WorksheetOptions> </x:ExcelWorksheet> <x:ExcelWorksheet> <x:Name>data2</x:Name> <x:WorksheetOptions> <x:Selected/> <x:ProtectContents>False</x:ProtectContents> <x:ProtectObjects>False</x:ProtectObjects> <x:ProtectScenarios>False</x:ProtectScenarios> </x:WorksheetOptions> </x:ExcelWorksheet> </x:ExcelWorksheets> </x:ExcelWorkbook> </xml>
<table x:str border=0 cellpadding=0 cellspacing=0 width=128 style='border-collapse: collapse;table-layout:fixed;width:96pt'> <col width=64 span=2 style='width:48pt'> <tr height=17 style='height:12.75pt'> <td height=17 width=64 style='height:12.75pt;width:48pt'>S1_R1_C1</td> <td width=64 style='width:48pt'>S1_R1_C2</td> <td width=64 style='width:48pt'>S1_R1_C3</td> </tr> <tr height=17 style='height:12.75pt'> <td height=17 width=64 style='height:12.75pt;width:48pt'>S1_R2_C1</td> <td width=64 style='width:48pt'>S1_R2_C2</td> <td width=64 style='width:48pt'>S1_R2_C3</td> </tr> </table> <xml> <x:ExcelWorkbook> <x:ActiveSheet>1</x:ActiveSheet> </x:ExcelWorkbook> </xml> <!-- This should fillup the second worksheet but it is till write into the 1st one --> <!-- S2_R1_C1 S2_R1_C2 S2_R1_C3 --> <table x:str border=0 cellpadding=0 cellspacing=0 width=128 style='border-collapse: collapse;table-layout:fixed;width:96pt'> <col width=64 span=2 style='width:48pt'> <tr height=17 style='height:12.75pt'> <td height=17 width=64 style='height:12.75pt;width:48pt'>S2_R1_C1</td> <td width=64 style='width:48pt'>S2_R1_C2</td> <td width=64 style='width:48pt'>S2_R1_C3</td> </tr> <tr height=17 style='height:12.75pt'> <td height=17 style='height:12.75pt'>Row2</td> <td>Col2</td> </tr> </table>
</body> </html>
Then I found that if you have multiple worksheets, then you have to use the <x:WorksheetSource> tag to specify the corresponding worksheet HTML file. This is an excerpt from the MS Office HTML and XML Reference: "When a workbook contains a single worksheet, the Name, WorksheetOptions, and WorksheetSource subelements are required and stored in the workbook HTML file. When a workbook contains multiple worksheets, only the Name and WorksheetSource subelements are required in the workbook HTML file. The WorksheetOptions element is specified in the corresponding worksheet HTML file as a subelement of the XML element." Here is an example: <x:ExcelWorkbook> <x:ExcelWorksheets> <x:ExcelWorksheet> <x:Name>Sheet1</x:Name> <x:WorksheetSource HRef="./Book4_files/sheet001.htm"/> </x:ExcelWorksheet> <x:ExcelWorksheet> <x:Name>Sheet2</x:Name> <x:WorksheetSource HRef="./Book4_files/sheet002.htm"/> </x:ExcelWorksheet> <x:ExcelWorksheet> <x:Name>Sheet3</x:Name> <x:WorksheetSource HRef="./Book4_files/sheet003.htm"/> </x:ExcelWorksheet> <x:ExcelWorksheet> <x:Name>MyChart</x:Name> <x:WorksheetSource HRef="./Book4_files/chart001.htm"/> <x:WorksheetType>Chart</x:WorksheetType> </x:ExcelWorksheet> </x:ExcelWorksheets> </x:ExcelWorkbook> Decided to give my users the option to export as Excel 2003+ (generate XML Spreadsheet format file) or export a set of .csv files. Thanks- Liz
|
|
|
|
 |
|
 |
This is ingenious - I had screeds of code by which I was trying to do this same sort of thing (without much success) and I ended up removing all of it and using your very neat little piece of code instead!
|
|
|
|
 |
|
 |
I tried converting to VB:
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim path As String
path = "c:\\test.xls"
Dim sw As StreamWriter = New StreamWriter(path)
Dim hw = New HtmlTextWriter(sw)
gvEditDetail.RenderControl(hw)
end sub
though it compiled , the app yields an error:
Control 'ctl00_ContentPlaceHolder1_gvEditDetail' of type 'GridView' must be placed inside a form tag with runat=server.
I am using a content_placeholder on the page and apparently it contains it's own <form runat="server"></form> tag
This routine seems to have difficulty with that.
Any suggestions about using it with a Masterpages's content placeholder?
Thanks.
|
|
|
|
 |
|
 |
It seems that you have actually inserted the DataGrid into your page, within a placeholder "ContentPlaceHolder1".
You need not do this. This generates an output to a file, not a page.
If you look at the original code, the DataGrid is created temporarily in memory, then its RenderControl method is used to generate the right output into a file through an HtmlTextWriter to a stream.
Remove your gvEditDetail from the page and try inserting the VB equivalent of the first lines of code that create the Datagrid and binds it into your Button2_Click handler.
Ben
|
|
|
|
 |
|
 |
This is not how you export any kind of data to any other data format. There are various data transformation methods including xml transformer or DTS packages, SSIS, or simply Data reconstruction. But, you do not ever export to html then hope an external application will understand html then save it using its own transform method.
Horrible horrible article.
|
|
|
|
 |
|
 |
"horrible" - that's a little harsh, n'est-ce pas?
Excel has official support for HTML data - just go to File->Open, and you'll see "*.html" files in its list of openable formats. All I've done here is to change the file extension to force Excel to open the file rather than a web browser.
Certainly this method doesn't work for all situations, but for straightforward, one-way transfer of raw data from code to Excel (along with style options), I've yet to find a simpler method. If you have, however, then please write it up in an article for all our benefit.
|
|
|
|
 |