一、asp.net中導(dǎo)出Excel的方法:
在asp.net中導(dǎo)出Excel有兩種方法,一種是將導(dǎo)出的文件存放在服務(wù)器某個(gè)文件夾下面,然后將文件地址輸出在瀏覽器上;一種是將文件直接將文件輸出流寫給瀏覽器。在Response輸出時(shí),t分隔的數(shù)據(jù),導(dǎo)出Excel時(shí),等價(jià)于分列,n等價(jià)于換行。
1、將整個(gè)html全部輸出Excel
此法將html中所有的內(nèi)容,如按鈕,表格,圖片等全部輸出到Excel中。
復(fù)制代碼 代碼如下:
Response.Clear();
Response.Buffer= true;
Response.AppendHeader("Content-Disposition","attachment;filename="+DateTime.Now.ToString("yyyyMMdd")+".xls");
Response.ContentEncoding=System.Text.Encoding.UTF8;
Response.ContentType = "application/vnd.ms-excel";
this.EnableViewState = false;
這里我們利用了ContentType屬性,它默認(rèn)的屬性為text/html,這時(shí)將輸出為超文本,即我們常見的網(wǎng)頁(yè)格式到客戶端,如果改為ms-excel將將輸出excel格式,也就是說(shuō)以電子表格的格式輸出到客戶端,這時(shí)瀏覽器將提示你下載保存。ContentType的屬性還包括:image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword 。同理,我們也可以輸出(導(dǎo)出)圖片、word文檔等。下面的方法,也均用了這個(gè)屬性。
2、將DataGrid控件中的數(shù)據(jù)導(dǎo)出Excel
上述方法雖然實(shí)現(xiàn)了導(dǎo)出的功能,但同時(shí)把按鈕、分頁(yè)框等html中的所有輸出信息導(dǎo)了進(jìn)去。而我們一般要導(dǎo)出的是數(shù)據(jù),DataGrid控件上的數(shù)據(jù)。
復(fù)制代碼 代碼如下:
System.Web.UI.Control ctl=this.DataGrid1;
//DataGrid1是你在窗體中拖放的控件
HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename=Excel.xls");
HttpContext.Current.Response.Charset ="UTF-8";
HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.Default;
HttpContext.Current.Response.ContentType ="application/ms-excel";
ctl.Page.EnableViewState =false;
System.IO.StringWriter tw = new System.IO.StringWriter() ;
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter (tw);
ctl.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
如果你的DataGrid用了分頁(yè),它導(dǎo)出的是當(dāng)前頁(yè)的信息,也就是它導(dǎo)出的是DataGrid中顯示的信息。而不是你select語(yǔ)句的全部信息。
為方便使用,寫成方法如下:
復(fù)制代碼 代碼如下:
public void DGToExcel(System.Web.UI.Control ctl)
{
HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename=Excel.xls");
HttpContext.Current.Response.Charset ="UTF-8";
HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.Default;
HttpContext.Current.Response.ContentType ="application/ms-excel";
ctl.Page.EnableViewState =false;
System.IO.StringWriter tw = new System.IO.StringWriter() ;
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter (tw);
ctl.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
}
用法:DGToExcel(datagrid1);
頁(yè)面中需要添加下面這個(gè)空方法.
public override void VerifyRenderingInServerForm(Control control)
{
}
3、將DataSet中的數(shù)據(jù)導(dǎo)出Excel
有了上邊的思路,就是將在導(dǎo)出的信息,輸出(Response)客戶端,這樣就可以導(dǎo)出了。那么把DataSet中的數(shù)據(jù)導(dǎo)出,也就是把DataSet中的表中的各行信息,以ms-excel的格式Response到http流,這樣就OK了。說(shuō)明:參數(shù)ds應(yīng)為填充有數(shù)據(jù)表的DataSet,文件名是全名,包括后綴名,如Excel2006.xls
復(fù)制代碼 代碼如下:
public void CreateExcel(DataSet ds,string FileName)
{
HttpResponse resp;
resp = Page.Response;
resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
resp.AppendHeader("Content-Disposition", "attachment;filename="+FileName);
string colHeaders= "", ls_item="";
//定義表對(duì)象與行對(duì)象,同時(shí)用DataSet對(duì)其值進(jìn)行初始化
DataTable dt=ds.Tables[0];
DataRow[] myRow=dt.Select();//可以類似dt.Select("id>10")之形式達(dá)到數(shù)據(jù)篩選目的
int i=0;
int cl=dt.Columns.Count;
//取得數(shù)據(jù)表各列標(biāo)題,各標(biāo)題之間以t分割,最后一個(gè)列標(biāo)題后加回車符
for(i=0;icl;i++)
{
if(i==(cl-1))//最后一列,加n
{
colHeaders +=dt.Columns[i].Caption.ToString() +"n";
}
else
{
colHeaders+=dt.Columns[i].Caption.ToString()+"t";
}
}
resp.Write(colHeaders);
//向HTTP輸出流中寫入取得的數(shù)據(jù)信息
//逐行處理數(shù)據(jù)
foreach(DataRow row in myRow)
{
//當(dāng)前行數(shù)據(jù)寫入HTTP輸出流,并且置空l(shuí)s_item以便下行數(shù)據(jù)
for(i=0;icl;i++)
{
if(i==(cl-1))//最后一列,加n
{
ls_item +=row[i].ToString()+"n";
}
else
{
ls_item+=row[i].ToString()+"t";
}
}
resp.Write(ls_item);
ls_item="";
}
resp.End();
}
4、將dataview導(dǎo)出excel
若想實(shí)現(xiàn)更加富于變化或者行列不規(guī)則的excel導(dǎo)出時(shí),可用本法。
復(fù)制代碼 代碼如下:
public void OutputExcel(DataView dv,string str)
{
//dv為要輸出到Excel的數(shù)據(jù),str為標(biāo)題名稱
GC.Collect();
Application excel;// = new Application();
int rowIndex=4;
int colIndex=1;
_Workbook xBk;
_Worksheet xSt;
excel= new ApplicationClass();
xBk = excel.Workbooks.Add(true);
xSt = (_Worksheet)xBk.ActiveSheet;
//
//取得標(biāo)題
//
foreach(DataColumn col in dv.Table.Columns)
{
colIndex++;
excel.Cells[4,colIndex] = col.ColumnName;
xSt.get_Range(excel.Cells[4,colIndex],excel.Cells[4,colIndex]).HorizontalAlignment = XlVAlign.xlVAlignCenter;//設(shè)置標(biāo)題格式為居中對(duì)齊
}
//
//取得表格中的數(shù)據(jù)
//
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;//設(shè)置日期型的字段格式為居中對(duì)齊
}
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;//設(shè)置字符型的字段格式為居中對(duì)齊
}
else
{
excel.Cells[rowIndex,colIndex] = row[col.ColumnName].ToString();
}
}
}
//
//加載一個(gè)合計(jì)行
//
int rowSum = rowIndex + 1;
int colSum = 2;
excel.Cells[rowSum,2] = "合計(jì)";
xSt.get_Range(excel.Cells[rowSum,2],excel.Cells[rowSum,2]).HorizontalAlignment = XlHAlign.xlHAlignCenter;
//
//設(shè)置選中的部分的顏色
//
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;//設(shè)置為淺黃色,共計(jì)有56種
//
//取得整個(gè)報(bào)表的標(biāo)題
//
excel.Cells[2,2] = str;
//
//設(shè)置整個(gè)報(bào)表的標(biāo)題格式
//
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;
//
//設(shè)置報(bào)表表格為最適應(yīng)寬度
//
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();
//
//設(shè)置整個(gè)報(bào)表的標(biāo)題為跨列居中
//
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;
//
//繪制邊框
//
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;//設(shè)置左邊線加粗
xSt.get_Range(excel.Cells[4,2],excel.Cells[4,colIndex]).Borders[XlBordersIndex.xlEdgeTop].Weight = XlBorderWeight.xlThick;//設(shè)置上邊線加粗
xSt.get_Range(excel.Cells[4,colIndex],excel.Cells[rowSum,colIndex]).Borders[XlBordersIndex.xlEdgeRight].Weight = XlBorderWeight.xlThick;//設(shè)置右邊線加粗
xSt.get_Range(excel.Cells[rowSum,2],excel.Cells[rowSum,colIndex]).Borders[XlBordersIndex.xlEdgeBottom].Weight = XlBorderWeight.xlThick;//設(shè)置下邊線加粗
//
//顯示效果
//
excel.Visible=true;
//xSt.Export(Server.MapPath(".")+""+this.xlfile.Text+".xls",SheetExportActionEnum.ssExportActionNone,Microsoft.Office.Interop.OWC.SheetExportFormat.ssExportHTML);
xBk.SaveCopyAs(Server.MapPath(".")+""+this.xlfile.Text+".xls");
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="GB2312";
Response.ContentEncoding=System.Text.Encoding.UTF8;
// 添加頭信息,為"文件下載/另存為"對(duì)話框指定默認(rèn)文件名
Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(file.Name));
// 添加頭信息,指定文件大小,讓瀏覽器能夠顯示下載進(jìn)度
Response.AddHeader("Content-Length", file.Length.ToString());
// 指定返回的是一個(gè)不能被客戶端讀取的流,必須被下載
Response.ContentType = "application/ms-excel";
// 把文件流發(fā)送到客戶端
Response.WriteFile(file.FullName);
// 停止頁(yè)面的執(zhí)行
Response.End();
}
上面的方面,均將要導(dǎo)出的excel數(shù)據(jù),直接給瀏覽器輸出文件流,下面的方法是首先將其存到服務(wù)器的某個(gè)文件夾中,然后把文件發(fā)送到客戶端。這樣可以持久的把導(dǎo)出的文件存起來(lái),以便實(shí)現(xiàn)其它功能。
5、將excel文件導(dǎo)出到服務(wù)器上,再下載。
二、winForm中導(dǎo)出Excel的方法:
1、方法1:
復(fù)制代碼 代碼如下:
SqlConnection conn=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"]);
SqlDataAdapter da=new SqlDataAdapter("select * from tb1",conn);
DataSet ds=new DataSet();
da.Fill(ds,"table1");
DataTable dt=ds.Tables["table1"];
string name=System.Configuration.ConfigurationSettings.AppSettings["downloadurl"].ToString()+DateTime.Today.ToString("yyyyMMdd")+new Random(DateTime.Now.Millisecond).Next(10000).ToString()+".csv";//存放到web.config中downloadurl指定的路徑,文件格式為當(dāng)前日期+4位隨機(jī)數(shù)
FileStream fs=new FileStream(name,FileMode.Create,FileAccess.Write);
StreamWriter sw=new StreamWriter(fs,System.Text.Encoding.GetEncoding("gb2312"));
sw.WriteLine("自動(dòng)編號(hào),姓名,年齡");
foreach(DataRow dr in dt.Rows)
{
sw.WriteLine(dr["ID"]+","+dr["vName"]+","+dr["iAge"]);
}
sw.Close();
Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(name));
Response.ContentType = "application/ms-excel";// 指定返回的是一個(gè)不能被客戶端讀取的流,必須被下載
Response.WriteFile(name); // 把文件流發(fā)送到客戶端
Response.End();
public void Out2Excel(string sTableName,string url)
{
Excel.Application oExcel=new Excel.Application();
Workbooks oBooks;
Workbook oBook;
Sheets oSheets;
Worksheet oSheet;
Range oCells;
string sFile="",sTemplate="";
//
System.Data.DataTable dt=TableOut(sTableName).Tables[0];
sFile=url+"myExcel.xls";
sTemplate=url+"MyTemplate.xls";
//
oExcel.Visible=false;
oExcel.DisplayAlerts=false;
//定義一個(gè)新的工作簿
oBooks=oExcel.Workbooks;
oBooks.Open(sTemplate,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing, Type.Missing, Type.Missing);
oBook=oBooks.get_Item(1);
oSheets=oBook.Worksheets;
oSheet=(Worksheet)oSheets.get_Item(1);
//命名該sheet
oSheet.Name="Sheet1";
oCells=oSheet.Cells;
//調(diào)用dumpdata過(guò)程,將數(shù)據(jù)導(dǎo)入到Excel中去
DumpData(dt,oCells);
//保存
oSheet.SaveAs(sFile,Excel.XlFileFormat.xlTemplate,Type.Missing,Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing);
oBook.Close(false, Type.Missing,Type.Missing);
//退出Excel,并且釋放調(diào)用的COM資源
oExcel.Quit();
GC.Collect();
KillProcess("Excel");
}
private void KillProcess(string processName)
{
System.Diagnostics.Process myproc= new System.Diagnostics.Process();
//得到所有打開的進(jìn)程
try
{
foreach (Process thisproc in Process.GetProcessesByName(processName))
{
if(!thisproc.CloseMainWindow())
{
thisproc.Kill();
}
}
}
catch(Exception Exc)
{
throw new Exception("",Exc);
}
}
2、方法2:
復(fù)制代碼 代碼如下:
protected void ExportExcel()
{
gridbind();
if(ds1==null) return;
string saveFileName="";
// bool fileSaved=false;
SaveFileDialog saveDialog=new SaveFileDialog();
saveDialog.DefaultExt ="xls";
saveDialog.Filter="Excel文件|*.xls";
saveDialog.FileName ="Sheet1";
saveDialog.ShowDialog();
saveFileName=saveDialog.FileName;
if(saveFileName.IndexOf(":")0) return; //被點(diǎn)了取消
// excelapp.Workbooks.Open (App.path 工程進(jìn)度表.xls)
Excel.Application xlApp=new Excel.Application();
object missing=System.Reflection.Missing.Value;
if(xlApp==null)
{
MessageBox.Show("無(wú)法創(chuàng)建Excel對(duì)象,可能您的機(jī)子未安裝Excel");
return;
}
Excel.Workbooks workbooks=xlApp.Workbooks;
Excel.Workbook workbook=workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
Excel.Worksheet worksheet=(Excel.Worksheet)workbook.Worksheets[1];//取得sheet1
Excel.Range range;
string oldCaption=Title_label .Text.Trim ();
long totalCount=ds1.Tables[0].Rows.Count;
long rowRead=0;
float percent=0;
worksheet.Cells[1,1]=Title_label .Text.Trim ();
//寫入字段
for(int i=0;ids1.Tables[0].Columns.Count;i++)
{
worksheet.Cells[2,i+1]=ds1.Tables[0].Columns.ColumnName;
range=(Excel.Range)worksheet.Cells[2,i+1];
range.Interior.ColorIndex = 15;
range.Font.Bold = true;
}
//寫入數(shù)值
Caption .Visible = true;
for(int r=0;rds1.Tables[0].Rows.Count;r++)
{
for(int i=0;ids1.Tables[0].Columns.Count;i++)
{
worksheet.Cells[r+3,i+1]=ds1.Tables[0].Rows[r];
}
rowRead++;
percent=((float)(100*rowRead))/totalCount;
this.Caption.Text= "正在導(dǎo)出數(shù)據(jù)["+ percent.ToString("0.00") +"%]...";
Application.DoEvents();
}
worksheet.SaveAs(saveFileName,missing,missing,missing,missing,missing,missing,missing,missing);
this.Caption.Visible= false;
this.Caption.Text= oldCaption;
range=worksheet.get_Range(worksheet.Cells[2,1],worksheet.Cells[ds1.Tables[0].Rows.Count+2,ds1.Tables[0].Columns.Count]);
range.BorderAround(Excel.XlLineStyle.xlContinuous,Excel.XlBorderWeight.xlThin,Excel.XlColorIndex.xlColorIndexAutomatic,null);
range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].ColorIndex = Excel.XlColorIndex.xlColorIndexAutomatic;
range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].LineStyle =Excel.XlLineStyle.xlContinuous;
range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].Weight =Excel.XlBorderWeight.xlThin;
if(ds1.Tables[0].Columns.Count>1)
{
range.Borders[Excel.XlBordersIndex.xlInsideVertical].ColorIndex=Excel.XlColorIndex.xlColorIndexAutomatic;
}
workbook.Close(missing,missing,missing);
xlApp.Quit();
}
三、附注:
雖然都是實(shí)現(xiàn)導(dǎo)出excel的功能,但在asp.net和winform的程序中,實(shí)現(xiàn)的代碼是各不相同的。在asp.net中,是在服務(wù)器端讀取數(shù)據(jù),在服務(wù)器端把數(shù)據(jù)以ms-excel的格式,以Response輸出到瀏覽器(客戶端);而在winform中,是把數(shù)據(jù)讀到客戶端(因?yàn)閣inform運(yùn)行端就是客戶端),然后調(diào)用客戶端安裝的office組件,將讀到的數(shù)據(jù)寫在excel
您可能感興趣的文章:- winform中的ListBox和ComboBox綁定數(shù)據(jù)用法實(shí)例
- WinForm實(shí)現(xiàn)為ComboBox綁定數(shù)據(jù)源并提供下拉提示功能
- C#(WinForm) ComboBox和ListBox添加項(xiàng)及設(shè)置默認(rèn)選擇項(xiàng)
- 綁定winform中DataGrid
- C#在winform中實(shí)現(xiàn)數(shù)據(jù)增刪改查等功能
- winform導(dǎo)出dataviewgrid數(shù)據(jù)為excel的方法
- Winform實(shí)現(xiàn)調(diào)用asp.net數(shù)據(jù)接口實(shí)例
- C#數(shù)據(jù)導(dǎo)入/導(dǎo)出Excel文件及winForm導(dǎo)出Execl總結(jié)
- WinForm中窗體間的數(shù)據(jù)傳遞交互的一些方法
- WinForm中comboBox控件數(shù)據(jù)綁定實(shí)現(xiàn)方法