Introduction
Excel is so powerful that it can easily successfully open not only excel itself, but also CSV format files, Tab format, website table format and other file formats. It’s so smart that it can automatically recognize number, character string and can easily automatically transfer 11+ digital natural numbers to scientific notation. For example, if you input number ”123456789012” in a cell, the number will be changed as “1.23457E+11”.
Background
Because Excel is powerful and useful, people always export data to Excel for future use. Here I am introducing several methods of exporting data to Excel. Export Data to Excel through ASP.NET. Store the output file in a folder of server and put the file address on browser. Or directly write the file string on browser. When Response exporting,data divided by “t” equals columns and “n” means rows. Now let’s enjoy the show…
Using the code
Solution 1, Export all HTML data to Excel
This method will transfer all the content in HTML, such as button, table, images and others to Excel.
Here we make use of “ContentType” property which the default set is text/HTML. And hypertext will be exported to client. If we change it to ms-excel, it will be exported as Excel format and your browser will remind you download and store it. The property of “ContentType” includes image/JPEG, text/HTML, image/GIF and vnd.ms-excel/msword.
Solution 2, Export Data from DataGrid to Excel
Although the method above can help you export data, it exports all data information such as button, images from HTML which we may not want to export. Usually, we only need export data stored in DatGrid.
If you have pages in your DataGrid, it only exports the information of the first page, maybe not all information you select.
Actually we can write like this:
Method:DGToExcel(datagrid1);
Solution 3, Export Data from DataSet to Excel
According to the methods above, we can easily export data from DataSet to Excel. We just need response rows information of DataSet table as ms-excel format to http string. Note: ds should be DataSet with information filled Datatable. File name should be full including suffix. For example, execl2006.xls
Solution 4, Export Data from Datview to Excel
If you want to export data to Excel with irregular rows or columns, you can use this method.
//
//Obtain data from table
//
foreach(DataRowView row in dv)
{
rowIndex ++;
colIndex = 1;
foreach(DataColumn col in dv.Table.Columns)
{
colIndex ++;
if(col.DataType == System.Type.GetType("System.DateTime"))
{
excel.Cells[rowIndex,colIndex]
= (Convert.ToDateTime(row[col.ColumnName].ToString())).ToString("yyyy-MM-dd");
xSt.get_Range(excel.Cells[rowIndex,colIndex],excel.Cells
[rowIndex,colIndex]).HorizontalAlignment
= XlVAlign.xlVAlignCenter;// Set the style as middle
}
else
if(col.DataType == System.Type.GetType("System.String"))
{
excel.Cells[rowIndex,colIndex] = "'"+row[col.ColumnName].ToString();
xSt.get_Range(excel.Cells[rowIndex,colIndex],excel.Cells
[rowIndex,colIndex]).HorizontalAlignment = XlVAlign.xlVAlignCenter;
// Set the style as middle
}
else
{
excel.Cells[rowIndex,colIndex] = row[col.ColumnName].ToString();
}
}
}
//
//load a Aggregate line
//
int rowSum = rowIndex + 1;
int colSum = 2;
excel.Cells[rowSum,2] = " Aggregate ";
xSt.get_Range(excel.Cells[rowSum,2],excel.Cells[rowSum,2]).HorizontalAlignment
= XlHAlign.xlHAlignCenter;
//
//Set color for the selected content
//
xSt.get_Range(excel.Cells[rowSum,colSum],excel.Cells[rowSum,colIndex]).Select();
xSt.get_Range(excel.Cells[rowSum,colSum],excel.Cells
[rowSum,colIndex]).Interior.ColorIndex
= 19;//more than 50 types of color for you to choose
//
//obtain title of the whole excelsheet
//
excel.Cells[2,2] = str;
//
//Set title format for the whole excelsheet
//
xSt.get_Range(excel.Cells[2,2],excel.Cells[2,2]).Font.Bold = true;
xSt.get_Range(excel.Cells[2,2],excel.Cells[2,2]).Font.Size = 22;
//
//Set fittest width
//
xSt.get_Range(excel.Cells[4,2],excel.Cells[rowSum,colIndex]).Select();
xSt.get_Range(excel.Cells[4,2],excel.Cells[rowSum,colIndex]).Columns.AutoFit();
//
//Set the tile as Cross and Middle
//
xSt.get_Range(excel.Cells[2,2],excel.Cells[2,colIndex]).Select();
xSt.get_Range(excel.Cells[2,2],excel.Cells[2,colIndex]).HorizontalAlignment
= XlHAlign.xlHAlignCenterAcrossSelection;
//
//Draw borders
//
xSt.get_Range(excel.Cells[4,2],excel.Cells[rowSum,colIndex]).Borders.LineStyle = 1;
xSt.get_Range(excel.Cells[4,2],excel.Cells[rowSum,2]).Borders
[XlBordersIndex.xlEdgeLeft].Weight
= XlBorderWeight.xlThick;// Set left line as bold
xSt.get_Range(excel.Cells[4,2],excel.Cells[4,colIndex]).Borders
[XlBordersIndex.xlEdgeTop].Weight
= XlBorderWeight.xlThick;// Set upper line as bold
xSt.get_Range(excel.Cells[4,colIndex],excel.Cells[rowSum,colIndex]).Borders
[XlBordersIndex.xlEdgeRight].Weight = XlBorderWeight.xlThick;//Set right line as bold
xSt.get_Range(excel.Cells[rowSum,2],excel.Cells[rowSum,colIndex]).Borders
[XlBordersIndex.xlEdgeBottom].Weight = XlBorderWeight.xlThick;//Set bottom line as bold
//
//Display effect
//
excel.Visible=true;
//xSt.Export(Server.MapPath(".")+");
xBk.SaveCopyAs(Server.MapPath(".")+"");
ds = null;
xBk.Close(false, null,null);
excel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xBk);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xSt);
xBk = null;
excel = null;
xSt = null;
GC.Collect();
string path = Server.MapPath(this.xlfile.Text+".xls");
System.IO.FileInfo file = new System.IO.FileInfo(path);
Response.Clear();
Response.Charset="UTF-8";
Response.ContentEncoding=System.Text.Encoding.UTF8;
//Add header, give a default file name for “File Download/Store as”
Response.AddHeader("Content-Disposition", "attachment; filename="
+ Server.UrlEncode(file.Name));
//Add header, set file size to enable browser display download progress
Response.AddHeader("Content-Length", file.Length.ToString());
//Set the return string is unavailable reading for client, and must be downloaded
Response.ContentType = "application/ms-excel";
//Send file string to client
Response.WriteFile(file.FullName);
//Stop execute
Response.End();
}
Solution 5, Export Data to Excel without Automation
By using this method you need download a free .net component and then do as the following codes showing(part) below:
System.Data.OleDb.OleDbCommand oleDbCommand1
= new System.Data.OleDb.OleDbCommand();
oleDbCommand1.CommandText = "select * from parts";
oleDbCommand1.Connection = oleDbConnection1;
System.Data.OleDb.OleDbCommand oleDbCommand2
= new System.Data.OleDb.OleDbCommand();
oleDbCommand2.CommandText = "select * from country";
oleDbCommand2.Connection = oleDbConnection1;
Spire.DataExport.Delegates.DataParamsEventHandler
(this.cellExport3_GetDataParams);
oleDbConnection1.Open();
try
{
cellExport3.SaveToFile();
}
finally
{
oleDbConnection1.Close();
}
}
private void cellExport3_GetDataParams
(object sender, Spire.DataExport.EventArgs.DataParamsEventArgs e)
{
if ((e.Sheet == 0) && (e.Col == 6))
{
e.FormatText =
(sender as Spire.DataExport.XLS.WorkSheet).ExportCell.DataFormats.Currency;
}
}
When you execute the codes above, you will get:
This solution can help you export data to Excel file which enables you open, write and modify with excel 2010. Although some special features of excel 2010 are still available, it's useful for Excel 2010.
2 more solutions via WinForm
Solution 6
Solution 7
</ds1.tables[0].columns.count;i++)>
Points of Interest
You may need some time to read this story
History
Keep a running update of any changes or improvements you've made here.
License
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
About the Author
loveyou999 |