ASP生成Excel文件方法
ASP生成Excel文件方法

ASP生成Excel文件方法ASP生成Excel文件方法方法一:导出到csv文件,存放在服务器端任一路径,然后给客户下载优点:1、可以进行身份认证后给客户下载,如果放到非web目录就没有对应的url,客户无法随时下载。
2、也是因为生成了文件,所以占用了服务器的空间,但是可以把文件名存放到数据库,再次给客户下载的时候不需要重复生成文件。
3、csv文件是文本文件,逗号隔开字段,回车隔开行,易于数据导入导出。
实现方法:SqlConnection conn=new SqlConnection("conn"]);SqlDataAdapter da=new SqlDataAdapter("select*from tb1",conn);DataSet ds=new DataSet();da.Fill(ds,"table1");DataTable dt=ds.T ables["table1"];string name="downloadurl"].ToString()+"yyyyMMdd")+new Random(".csv";//存放到web.config中downloadurl指定的路径,文件格式为当前日期+4位随机数FileStream fs=newFileStream(name,FileMode.Create,FileAccess.Write);StreamWriter sw=new StreamWriter(fs,"gb2312"));sw.WriteLine("自动编号,姓名,年龄");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";//指定返回的是一个不能被客户端读取的流,必须被下载Response.WriteFile(name);//把文件流发送到客户端Response.End();方法二:导出到csv文件,不存放到服务器,直接给浏览器输出文件流优点:1、随时生成,不需要占用资源2、可以结合身份认证3、同样利于数据交换实现方法:SqlConnection conn=new SqlConnection("conn"]);SqlDataAdapter da=new SqlDataAdapter("select*from tb1",conn);DataSet ds=new DataSet();da.Fill(ds,"table1");DataTable dt=ds.T ables["table1"];StringWriter sw=new StringWriter();sw.WriteLine("自动编号,姓名,年龄");foreach(DataRow dr in dt.Rows){sw.WriteLine(dr["ID"]+","+dr["vName"]+","+dr["iAge"]);}sw.Close();Response.AddHeader("Content-Disposition","attachment;filename=test.csv");Response.ContentType="application/ms-excel";Response.ContentEncoding="GB2312");Response.Write(sw);Response.End();对方法一,二补充一点,如果你希望导出的是xls文件分隔符用\t 就可以了,不要用逗号代码修改如下:sw.WriteLine("自动编号\t姓名\t年龄");foreach(DataRow dr in dt.Rows){sw.WriteLine(dr["ID"]+"\t"+dr["vName"]+"\t"+dr["iAge"]);}另外,修改输出的文件扩展名为xls即可。
asp表格导出EXCEL的方法修改

asp中表格导出到EXCEL的方法一、第一种表格导出到Word代码、导出到EXCEL代码<input type="hidden" name="out_word" onclick="vbscript:buildDoc" value="导出到word" class="notPrint"><input type="hidden" name="out_excel" onclick="AutomateExcel();" value="导出到excel" class="notPrint"><title>浏览器表格导出到Excel代码</title><input type="button" name="out_word" onclick="vbscript:buildDoc" value="导出到word" class="notPrint"><input type="button" name="out_word1" onclick="javascript:AutomateExcel() "value="导出到excel" class="notPrint"><table id="data" width="200" border="1"><tr><td>11</td><td>11</td></tr><tr><td>22</td><td>22</td></tr><tr><td>33</td><td>33</td></tr><tr><td>44 </td><td>44</td></tr></table><SCRIPT LANGUAGE="JavaScript"><!--function AutomateExcel(){// Start Excel and get Application object.var oXL = new ActiveXObject("Excel.Application");// Get a new workbook.var oWB = oXL.Workbooks.Add();var oSheet = oWB.ActiveSheet;var table = document.all.data;var hang = table.rows.length;var lie = table.rows(0).cells.length;// Add table headers going cell by cell.for (i=0;i<hang;i++){for (j=0;j<lie;j++){oSheet.Cells(i+1,j+1).Value = table.rows(i).cells(j).innerText; }}oXL.Visible = true;erControl = true;}//--></SCRIPT>导出到Word代码<script language="vbscript">Sub buildDocset table = document.all.datarow = table.rows.lengthcolumn = table.rows(1).cells.lengthSet objWordDoc = CreateObject("Word.Document")'objWordDoc.Application.Documents.Add theTemplate, False objWordDoc.Application.Visible=TrueDim theArray(20,10000)for i=0 to row-1for j=0 to column-1theArray(j+1,i+1) = table.rows(i).cells(j).innerTEXTnextnextobjWordDoc.Application.ActiveDocument.Paragraphs.Add.Range.InsertBefore("综合查询结果集") //显示表格标题objWordDoc.Application.ActiveDocument.Paragraphs.Add.Range.InsertBefore("") Set rngPara = objWordDoc.Application.ActiveDocument.Paragraphs(1).Range With rngPara.Bold = True //将标题设为粗体.ParagraphFormat.Alignment = 1 //将标题居中 = "隶书" //设定标题字体.Font.Size = 18 //设定标题字体大小End WithSet rngCurrent = objWordDoc.Application.ActiveDocument.Paragraphs(3).Range Set tabCurrent = ObjWordDoc.Application.ActiveDocument.Tables.Add(rngCurrent,row,column)for i = 1 to columnobjWordDoc.Application.ActiveDocument.Tables(1).Rows(1).Cells(i).Range.Inse rtAfter theArray(i,1)objWordDoc.Application.ActiveDocument.Tables(1).Rows(1).Cells(i).Range.Para graphFormat.alignment=1nextFor i =1 to columnFor j = 2 to rowobjWordDoc.Application.ActiveDocument.Tables(1).Rows(j).Cells(i).Range.Inse rtAfter theArray(i,j)objWordDoc.Application.ActiveDocument.Tables(1).Rows(j).Cells(i).Range.Para graphFormat.alignment=1NextNextEnd Sub</SCRIPT>二、第二种如何在asp脚本里做个按钮可以将数据导出到excel表里-------------------------------------------------------------------------------方法一<input type="hidden" name="out_excel" onclick="AutomateExcel();" value="导出到excel" class="notPrint"><title>浏览器表格导出到Excel</title><input type="button" name="out_word1" onclick="java script:AutomateExcel() " value="导出到excel" class="notPrint"><table id="data" width="200" border="1"><tr><td>11</td><td>11</td></tr><tr><td>22</td><td>22</td></tr><tr><td>33</td><td>33</td></tr><tr><td>44 </td><td>44</td></tr></table><SCRIPT LANGUAGE="JavaScript"><!--function AutomateExcel(){// Start Excel and get Application object.var oXL = new ActiveXObject("Excel.Application");// Get a new workbook.var oWB = oXL.Workbooks.Add();var oSheet = oWB.ActiveSheet;var table = document.all.data;var hang = table.rows.length;var lie = table.rows(0).cells.length;// Add table headers going cell by cell.for (i=0;i<hang;i++){for (j=0;j<lie;j++){oSheet.Cells(i+1,j+1).Value = table.rows(i).cells(j).innerText;}}oXL.Visible = true;erControl = true;}//--></SCRIPT>方法二<%@ LANGUAGE="VBSCRIPT" %><%option explicit%><%%><!--#include file="conn.asp"--><HTML><HEAD><meta http-equiv="Content-Type" content="text/html; charset=gb2312"> <TITLE>生成EXCEL文件</TITLE></HEAD><body><%dim rs,sql,filename,fs,myfile,x,linkSet fs = server.CreateObject("scripting.filesystemobject")filename = "f:\online.xls"if fs.FileExists(filename) thenfs.DeleteFile(filename)end ifset myfile = fs.CreateTextFile(filename,true)Set rs = Server.CreateObject("ADODB.Recordset")sql = "select * from table"rs.Open sql,connif rs.EOF and rs.BOF thenelsedim strLine,responsestrstrLine=""For each x in rs.fieldsstrLine= strLine & & chr(9)Nextmyfile.writeline strLineDo while Not rs.EOFstrLine=""for each x in rs.FieldsstrLine= strLine & x.value & chr(9)nextmyfile.writeline strLiners.MoveNextloopend ifrs.Closeset rs = nothingconn.closeset conn = nothingset myfile = nothingSet fs=Nothing%></BODY></HTML>//是从数据库里直接读出来再转到EXCEL中.要在页面上显示稍改下就成. 如何关闭excel进程dim excelappset excelapp=createobject("excel.application")............excelapp.quit'必备,建议上面加上on error resume next防止未知错误不能执行到此行set excelapp = nothing三、强人介绍的四种方法一、使用OWC 什么是OWC OWC是Office Web Compent的缩写,即Microsoft的Office Web 组件,它为在Web中绘制图形提供了灵活的同时也是最基本的机制。
asp.net中使用npoi导出excel电子表格

中使用npoi导出excel电子表格NPOI是一个开源的C#读写Excel、WORD等微软OLE2组件文档的项目,可以在没有安装Office的情况下对Word或Excel文档进行读写操作。
一、添加引用1、将NPOI.dll、Ioniz.Zip.dll复制到web/bin 文件夹中;2、在common公用工具层添加引用,浏览找到NPOI.dll;二、类库代码在common中建立类库NPOIExcel.csusing System;using System.Collections.Generic;using System.Linq;using System.Web;using NPOI;using NPOI.HPSF;using NPOI.HSSF;using erModel;using NPOI.POIFS;using NPOI.Util;using System.IO;using System.Data;using System.Data.SqlClient;public class DataTableRenderT oExcel{/// <summary>/// DataTable导出到Excel文件/// </summary>/// <param name="dtSource">源DataTable</param>/// <param name="strHeaderText">表头文本</param>/// <param name="strFileName">保存位置</param>public static void DataTableToExcel(DataTable dtSource, string strHeaderText, string strFileName){using (MemoryStream ms = DataTableToExcel(dtSource, strHeaderText)){using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write)){byte[] data = ms.T oArray();fs.Write(data, 0, data.Length);fs.Flush();}}}/// <summary>/// DataTable导出到Excel的MemoryStream/// </summary>/// <param name="dtSource">源DataTable</param>/// <param name="strHeaderText">表头文本</param>public static MemoryStream DataTableToExcel(DataT able dtSource, string strHeaderText){HSSFWorkbook workbook = new HSSFWorkbook();HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet();#region 右击文件属性信息{DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();pany = "NPOI";workbook.DocumentSummaryInformation = dsi;SummaryInformation si = PropertySetFactory.CreateSummaryInformation();si.Author = "文件作者信息"; //填加xls文件作者信息si.ApplicationName = "创建程序信息"; //填加xls文件创建程序信息stAuthor = "最后保存者信息"; //填加xls文件最后保存者信息ments = "作者信息"; //填加xls文件作者信息si.Title = "标题信息"; //填加xls文件标题信息si.Subject = "主题信息";//填加文件主题信息si.CreateDateTime = System.DateTime.Now;workbook.SummaryInformation = si;}#endregionHSSFCellStyle dateStyle = (HSSFCellStyle)workbook.CreateCellStyle();HSSFDataFormat format = (HSSFDataFormat)workbook.CreateDataFormat();dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");//取得列宽int[] arrColWidth = new int[dtSource.Columns.Count];foreach (DataColumn item in dtSource.Columns){arrColWidth[item.Ordinal] = System.Text.Encoding.GetEncoding(936).GetBytes(item.Column Name.T oString()).Length;}for (int i = 0; i < dtSource.Rows.Count; i++){for (int j = 0; j < dtSource.Columns.Count; j++){int intTemp = System.Text.Encoding.GetEncoding(936).GetBytes(dtSource.Row s[i][j].ToString()).Length;if (intTemp > arrColWidth[j]){arrColWidth[j] = intTemp;}}}int rowIndex = 0;foreach (DataRow row in dtSource.Rows){#region 新建表,填充表头,填充列头,样式if (rowIndex == 65535 || rowIndex == 0){if (rowIndex != 0){sheet = (HSSFSheet)workbook.CreateSheet();}#region 表头及样式{HSSFRow headerRow = (HSSFRow)sheet.CreateRow(0);headerRow.HeightInPoints = 25;headerRow.CreateCell(0).SetCellValue(strHeaderText);HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle();headStyle.Alignment = erModel.HorizontalAlignment.LEFT; //左对齐HSSFFont font = (HSSFFont)workbook.CreateFont();font.FontHeightInPoints = 20;font.Boldweight = 700;headStyle.SetFont(font);headerRow.GetCell(0).CellStyle = headStyle;// sheet.AddMergedRegion(new Region(0, 0, 0, dtSource.Columns.Count - 1));//headerRow.Dispose();}#endregion#region 列头及样式{HSSFRow headerRow = (HSSFRow)sheet.CreateRow(1);HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle();//headStyle.Alignment = CellHorizontalAlignment.CENTER;HSSFFont font = (HSSFFont)workbook.CreateFont();font.FontHeightInPoints = 10;font.Boldweight = 700;headStyle.SetFont(font);foreach (DataColumn column in dtSource.Columns){headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);headerRow.GetCell(column.Ordinal).CellStyle = headStyle;//设置列宽sheet.SetColumnWidth(column.Ordinal,(arrColWidth[column.Ordinal] + 1) * 256);}// headerRow.Dispose();}#endregionrowIndex = 2;}#endregion#region 填充内容HSSFRow dataRow = (HSSFRow)sheet.CreateRow(rowIndex);foreach (DataColumn column in dtSource.Columns){HSSFCell newCell = (HSSFCell)dataRow.CreateCell(column.Ordinal);string drValue = row[column].ToString();switch (column.DataType.ToString()){case "System.String"://字符串类型newCell.SetCellValue(drValue);break;case "System.DateTime"://日期类型System.DateTime dateV;System.DateTime.TryParse(drValue, out dateV);newCell.SetCellValue(dateV);newCell.CellStyle = dateStyle;//格式化显示break;case "System.Boolean"://布尔型bool boolV = false;bool.TryParse(drValue, out boolV); newCell.SetCellValue(boolV); break;case "System.Int16"://整型case "System.Int32":case "System.Int64":case "System.Byte":int intV = 0;int.TryParse(drValue, out intV); newCell.SetCellValue(intV); break;case "System.Decimal"://浮点型case "System.Double":double doubV = 0;double.TryParse(drValue, out doubV); newCell.SetCellValue(doubV); break;case "System.DBNull"://空值处理newCell.SetCellValue("");break;default:newCell.SetCellValue("");break;}}#endregionrowIndex++;}using (MemoryStream ms = new MemoryStream()){workbook.Write(ms);ms.Flush();ms.Position = 0;sheet.Dispose();//workbook.Dispose();//一般只用写这一个就OK了,他会遍历并释放所有资源,但当前版本有问题所以只释放sheetreturn ms;}}/// <summary>读取excel/// 默认第一行为标头/// </summary>/// <param name="strFileName">excel文档路径</param> /// <returns></returns>public static DataT able Import(string strFileName){DataTable dt = new DataTable();HSSFWorkbook hssfworkbook;using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read)){hssfworkbook = new HSSFWorkbook(file);}HSSFSheet sheet = (HSSFSheet)hssfworkbook.GetSheetAt(0);System.Collections.IEnumerator rows = sheet.GetRowEnumerator();HSSFRow headerRow = (HSSFRow)sheet.GetRow(0);int cellCount = stCellNum;for (int j = 0; j < cellCount; j++){HSSFCell cell = (HSSFCell)headerRow.GetCell(j);dt.Columns.Add(cell.ToString());}for (int i = (sheet.FirstRowNum + 1); i <= stRowNum; i++){HSSFRow row = (HSSFRow)sheet.GetRow(i);DataRow dataRow = dt.NewRow();for (int j = row.FirstCellNum; j < cellCount; j++){if (row.GetCell(j) != null)dataRow[j] = row.GetCell(j).ToString();}dt.Rows.Add(dataRow);}return dt;}//以上是新增的。
asp.net里导出excel表方法汇总

HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
}
用法:ToExcel(datagrid1);
4、这个用dataview ,代码好长
//
//设置报表表格为最适应宽度
//
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();
}
//
//取得表格中的数据
//
foreach(DataRowView row in dv)
{
rowIndex ++;
colIndex = 1;
foreach(DataColumn col in dv.Table.Columns)
{
colIndex ++;
//
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;//设置为浅黄色,共计有56种
HttpContext.Current.Response.Charset ="UTF-8";
Asp.NetCore实现Excel导出功能的实现方法

Core实现Excel导出功能的实现⽅法⽬录安装 ClosedXML将数据导出成 CSV ⽂件将数据导出成 XLSX ⽂件下载 Excel在web应⽤程序开发时,或许你会遇到这样的需求,如何在 Core 中实现 excel 或者 word 的导⼊导出,在 NuGet 上有⼤量的⼯具包可以实现这样的功能,本篇就讨论下如何使⽤ ClosedXML 实现 Excel 数据导出。
安装 ClosedXML如果想实现 Excel 的导出功能,在 Core 中有很多的dll可以做到,其中的⼀个叫做 ClosedXML,你可以通过可视化界⾯ NuGet package manager 去安装,也可以使⽤命令⾏ NuGet package manager console 执⾏下⾯命令。
Install-Package ClosedXML将数据导出成 CSV ⽂件将数据导成 CSV ⽂件是⾮常简单的,毕竟每⾏数据都是⽤ , 隔开即可,可以⽤ NuGet 上的 CsvExport 或者AWright18.SimpleCSVExporter 去实现,当然你觉得⾃⼰很 ,可以亲⾃操⼑实现,下⾯我准备亲⾃实现⼀下,先看下⾯定义的 Author 类。
public class Author{public int Id { get; set; }public string FirstName { get; set; }public string LastName { get; set; }}然后塞⼀些数据到 authors 列表中,如下代码所⽰:List<Author> authors = new List<Author>{new Author { Id = 1, FirstName = "Joydip", LastName = "Kanjilal" },new Author { Id = 2, FirstName = "Steve", LastName = "Smith" },new Author { Id = 3, FirstName = "Anand", LastName = "Narayaswamy"}};定义⼀个 DownloadCommaSeperatedFile ⽅法,⽤于实现 Action 的 csv 导出功能。
asp.net生成Excel并导出下载五种实现方法

⽣成Excel并导出下载五种实现⽅法通过GridView(简评:⽅法⽐较简单,但是只适合⽣成格式简单的Excel,且⽆法保留VBA代码),页⾯⽆刷新aspx.cs部分复制代码代码如下:using System; using System.Collections; using System.Configuration; using System.Data; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Text; public partial class DataPage_NationDataShow : System.Web.UI.Page { private Data_Link link = new Data_Link(); private string sql; protected void Page_Load(object sender, EventArgs e) { Ajax.Utility.RegisterTypeForAjax(typeof(DataPage_NationDataShow)); } protected void btnExcel_Click(object sender, EventArgs e) { string strExcelName = "MyExcel"; strExcelName = strExcelName.Replace(@"/", ""); Data_Link link = new Data_Link(); string strSQL = this.hidParam.Value; DataSet ds = new DataSet(); ds = link.D_DataSet_Return(strSQL);//获得想要放⼊Excel的数据 gvExcel.Visible = true; gvExcel.DataSource = null; gvExcel.DataMember = ds.Tables[0].TableName; gvExcel.DataSource = ds.Tables[0]; gvExcel.DataBind(); ExportToExcel(this.Page, gvExcel, strExcelName); } protected void gvExcel_RowDataBound(object sender, GridViewRowEventArgs e) { } public override void VerifyRenderingInServerForm(Control control) { } /// <summary> /// ⼯具⽅法,Excel出⼒(解决乱码问题) /// </summary> ///<param name="page">调⽤页⾯</param> /// <param name="excel">Excel数据</param> /// <param name="fileName">⽂件名</param> public void ExportToExcel(System.Web.UI.Page page, GridView excel, string fileName) { try { foreach (GridViewRow row in excel.Rows) { for (int i = 0; i < row.Cells.Count; i++) { excel.HeaderRow.Cells[i].BackColor = System.Drawing.Color.Yellow; } } excel.Font.Size = 10; excel.AlternatingRowStyle.BackColor =System.Drawing.Color.LightCyan; excel.RowStyle.Height = 25; page.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName); page.Response.Charset = "utf-8"; page.Response.ContentType = "application/vnd.ms-excel"; page.Response.Write("<meta http-equiv=Content-Type content=text/html;charset=utf-8>");excel.Page.EnableViewState = false; excel.Visible = true; excel.HeaderStyle.Reset(); excel.AlternatingRowStyle.Reset(); System.IO.StringWriter oStringWriter = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter); excel.RenderControl(oHtmlTextWriter);page.Response.Write(oStringWriter.ToString()); page.Response.End(); excel.DataSource = null; excel.Visible = false; } catch (Exception e) { } } }aspx部分复制代码代码如下:<head runat="server"> <script type="text/javascript"> //Excel DownLoad function excelExport(){ var hidText = document.getElementById("hidParam"); hidText.value = "some params"; document.getElementById("ExcelOutput").click(); } </script> </head> <body onload="pageInit()"> <form id="form1"runat="server"> <input type="button" value="EXCEL下载" style="width:100px;" onclick="excelExport()" id="excelBut" /><input id="hidParam" type="text" runat="server" style="display:none;"/> <asp:Button runat="server" ID="ExcelOutput"style="display:none" Text= "EXCEL出⼒" Width="0px" onclick="btnExcel_Click" UseSubmitBehavior="false"/><asp:GridView ID="gvExcel" runat="server" Height="95px" OnRowDataBound="gvExcel_RowDataBound" Visible="False"> </asp:GridView> </form> </body>在刚才的aspx.cs代码中复制代码代码如下:foreach (GridViewRow row in excel.Rows) { for (int i = 0; i < row.Cells.Count; i++) { excel.HeaderRow.Cells[i].BackColor = System.Drawing.Color.Yellow; } }这部分是给表头添加样式。
ASP导出为Word或Excel的最简单方法

ASP导出为Word或Excel的最简单⽅法我在做⼀项⽬时,客户要求要将从数据库中获取数据后的ASP页⾯导出成EXCEL或WORD⽂档。
经本⼈试验后找出了最简单的⽅法:在ASP⽂件的最开头位置加⼊下⾯的代码就可以了,⾮常简单。
Asp代码1. EXCEL2. <%3. Response.ContentType ="application/vnd.ms-excel"4. Response.AddHeader "Content-Disposition", "attachment; filename=红宝⽹络表格.xls"5. %>6.7. WORD8. <%9. Response.ContentType ="application/vnd.ms-word"10. Response.AddHeader "Content-Disposition", "attachment; filename=红宝⽹络⽂档.doc"11. %>导出为WORD时,若⽂档中含有表格,需要打打印,则要在导出的页⾯中加⼊下⾯的样式。
Css代码1. <style type="text/css">2. <!--3. table{4. border-collapse:collapse;border:none;mso-border-alt:solid windowtext .5pt;5. mso-yfti-tbllook:480;mso-padding-alt:0cm 5.4pt 0cm 5.4pt;mso-border-insideh:6. .5pt solid windowtext;mso-border-insidev:.5pt solid windowtext;border-left:solid windowtext 1.0pt;border-top:solid windowtext 1.0pt;7. }8. td{9. border-top:none;border-left:10. none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;11. mso-border-top-alt:solid windowtext .5pt;mso-border-left-alt:solid windowtext .5pt;12. mso-border-alt:solid windowtext .5pt;padding:0cm 5.4pt 0cm 5.4pt;13. }14. -->15. </style>我打字系统项⽬中的⼀个导出为EXCEL⽂件的实例代码如下:Asp代码1. <!--#include file="hbwlConfig.asp" -->2. <%Response.ContentType ="application/vnd.ms-excel"3. Response.AddHeader "Content-Disposition", "attachment; filename=chengji.xls"%>4. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "/TR/xhtml1/DTD/xhtml1-transitional.dtd">5. <html xmlns="/1999/xhtml">6. <head>7. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />8. <title>打字成绩</title>9. <style type="text/css">10. .tableWg {border:1px solid #9bbde6;}11. .tableWg tr{text-align:center;}12. .tableWg td{ border-bottom:1px dotted #9bbde6; border-right:1px dotted #9bbde6;}13. </style>14. </head>15. <body>16. <%sql=session("chengjisql")17. response.Write hbwl.dbSelect(sql,0,1,"",0,"",0,"tableWg")%>18. </body>19. </html>20. <%set hbwl=nothing%>。
Asp.net生成Excel文件并下载(更新:解决使用迅雷下载页面而不是文件的问题)

生成Excel文件并下载(更新:解决使用迅雷下载页面而不是文件的问题)页面导航:→ → → → 正文内容生成Excel文件并下载 生成Excel文件并下载(更新:解决使用迅雷下载页面而不是文件的问题)这里采用的是在服务端先生成Excel文件,然后利用文件地址下载的方法。
生成Excel文件的方法,见:.Net创建Excel文件(插入数据、修改格式、生成图表)的方法先试用Response.WriteFile的方法:复制代码代码如下:FileInfo fi = new FileInfo(excelFile);//excelFile为文件在服务器上的地址HttpResponse contextResponse = HttpContext.Current.Response; contextResponse.Clear();contextResponse.Buffer = true;contextResponse.Charset = "GB2312"; //设置了类型为中文防止乱码的出现contextResponse.AppendHeader("Content-Disposition",String.Format("attachment;filename={0}", excelName)); //定义输出文件和文件名contextResponse.AppendHeader("Content-Length", fi.Length.ToString()); contextResponse.ContentEncoding = Encoding.Default; contextResponse.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。
contextResponse.WriteFile(fi.FullName);contextResponse.Flush();contextResponse.End();其中第一行的excelFile为Excel文件在服务器上的地址,比如:“C:\Website\Excel\xx.xlsx”。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
ASP生成Excel文件方法方法一:导出到csv文件,存放在服务器端任一路径,然后给客户下载优点:1、可以进行身份认证后给客户下载,如果放到非web目录就没有对应的url,客户无法随时下载。
2、也是因为生成了文件,所以占用了服务器的空间,但是可以把文件名存放到数据库,再次给客户下载的时候不需要重复生成文件。
3、csv文件是文本文件,逗号隔开字段,回车隔开行,易于数据导入导出。
实现方法:SqlConnection conn=new SqlConnection("conn"]);SqlDataAdapter da=new SqlDataAdapter("select*from tb1",conn);DataSet ds=new DataSet();da.Fill(ds,"table1");DataTable dt=ds.Tables["table1"];string name="downloadurl"].ToString()+"yyyyMMdd")+newRandom(".csv";//存放到web.config中downloadurl指定的路径,文件格式为当前日期+4位随机数FileStream fs=newFileStream(name,FileMode.Create,FileAccess.Write);StreamWriter sw=new StreamWriter(fs,"gb2312"));sw.WriteLine("自动编号,姓名,年龄");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";//指定返回的是一个不能被客户端读取的流,必须被下载Response.WriteFile(name);//把文件流发送到客户端Response.End();方法二:导出到csv文件,不存放到服务器,直接给浏览器输出文件流优点:1、随时生成,不需要占用资源2、可以结合身份认证3、同样利于数据交换实现方法:SqlConnection conn=new SqlConnection("conn"]);SqlDataAdapter da=new SqlDataAdapter("select*from tb1",conn);DataSet ds=new DataSet();da.Fill(ds,"table1");DataTable dt=ds.Tables["table1"];StringWriter sw=new StringWriter();sw.WriteLine("自动编号,姓名,年龄");foreach(DataRow dr in dt.Rows){sw.WriteLine(dr["ID"]+","+dr["vName"]+","+dr["iAge"]);}sw.Close();Response.AddHeader("Content-Disposition","attachment;filename=test.csv");Response.ContentType="application/ms-excel";Response.ContentEncoding="GB2312");Response.Write(sw);Response.End();对方法一,二补充一点,如果你希望导出的是xls文件分隔符用\t就可以了,不要用逗号代码修改如下:sw.WriteLine("自动编号\t姓名\t年龄");foreach(DataRow dr in dt.Rows){sw.WriteLine(dr["ID"]+"\t"+dr["vName"]+"\t"+dr["iAge"]);}另外,修改输出的文件扩展名为xls即可。
方法三:从datagrid导出html代码,生成excel文件,给客户端下载优点:1、有固定的格式,样子好看(datagrid的样子)局限性:1、不适合数据交换,里面有html代码,比较乱,没有固定格式2、datagrid不能有分页、排序等,否则出错实现方法:Response.Clear();Response.Buffer=false;Response.Charset="GB2312";Response.AppendHeader("Content-Disposition","attachment;filename=test.xls");Response.ContentEncoding="GB2312");Response.ContentType="application/ms-excel";this.EnableViewState=false;oStringWriter=new ;oHtmlTextWriter=new ;;Response.Write(oStringWriter.ToString());Response.End();在这里说明一点:有的网友反映代码出现"没有dr["id"]"之类的错误,这个代码是按照我的数据结构来写的,到时候相关的字段要换成你自己的才是。
还有就是如果文件名需要中文的话,这么修改Response.AddHeader("Content-Disposition","attachment;filename="+"中文",".xls");目录一、环境配置二、ASP对Excel的基本操作三、ASP操作Excel生成数据表四、ASP操作Excel生成Chart图五、服务器端Excel文件浏览、下载、删除方案六、附录正文一、环境配置服务器端的环境配置从参考资料上看,微软系列的配置应该都行,即:1.Win9x+PWS+Office2.Win2000 Professional+PWS+Office3.Win2000 Server+IIS+Office目前笔者测试成功的环境是后二者。
Office的版本没有特殊要求,考虑到客户机配置的不确定性和下兼容特性,建议服务器端Office版本不要太高,以防止客户机下载后无法正确显示。
服务器端环境配置还有两个偶然的发现是:1.笔者开发机器上原来装有金山的WPS2002,结果Excel对象创建始终出现问题,卸载WPS2002后,错误消失。
2.笔者开发ASP代码喜欢用FrontPage,结果发现如果FrontPage打开(服务器端),对象创建出现不稳定现象,时而成功时而不成功。
扩展考察后发现,Office系列的软件如果在服务器端运行,则Excel对象的创建很难成功。
服务器端还必须要设置的一点是COM组件的操作权限。
在命令行键入"DCOMCNFG",则进入COM组件配置界面,选择Microsoft Excel后点击属性按钮,将三个单选项一律选择自定义,编辑中将Everyone加入所有权限。
保存完毕后重新启动服务器。
客户端的环境配置没发现什么特别讲究的地方,只要装有Office和IE 即可,版本通用的好象都可以。
二、ASP对Excel的基本操作1、建立Excel对象set objExcelApp=CreateObject("Excel.Application")objExcelApp.DisplayAlerts=false不显示警告2、新建Excel文件set objExcelBook=objExcelApp.ActiveWorkBook set objExcelSheets=objExcelBook.Worksheets setobjExcelSheet=objExcelBook.Sheets(1)3、读取已有Excel文件strAddr=Server.MapPath(".")"\Templet\Table.xls")set objExcelBook=objExcelApp.ActiveWorkBook set objExcelSheets=objExcelBook.Worksheets setobjExcelSheet=objExcelBook.Sheets(1)4、另存Excel文件objExcelBook.SaveAs strAddr&"\Temp\Table.xls"5、保存Excel文件objExcelBook.Save(笔者测试时保存成功,页面报错。
)6、退出Excel操作objExcelApp.Quit一定要退出set objExcelApp=Nothing三、ASP操作Excel生成数据表1、在一个范围内插入数据objExcelSheet.Range("B3:k3").Value=Array("67","87","5","9","7","45","45","54","54","10")2、在一个单元格内插入数据objExcelSheet.Cells(3,1).Value="Internet Explorer"3、选中一个范围4、单元格左边画粗线条5、单元格右边画粗线条6、单元格上边画粗线条7、单元格下边画粗线条8、单元格设定背景色9、合并单元格10、插入行11、插入列四、ASP操作Excel生成Chart图1、创建Chart图2、设定Chart图种类注:二维折线图,4;二维饼图,5;二维柱形图,51 3、设定Chart图标题"A test Chart"4、通过表格数据设定图形objExcelSheet.Range("A1:k5"),1 5、直接设定图形数据(推荐)"=""333""""={1,4,5,6,2}"6、绑定Chart图17、显示数据表8、显示图例五、服务器端Excel文件浏览、下载、删除方案浏览的解决方法很多,"Location.href=","Navigate","Response.Redirect"都可以实现,建议用客户端的方法,原因是给服务器更多的时间生成Excel文件。