日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

.net导出Excel

發布時間:2025/7/14 编程问答 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 .net导出Excel 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

2019獨角獸企業重金招聘Python工程師標準>>>

綜合參考了網上的方法,生成Excel文件提供下載,然后刪除生成的Excel文件。

1、引用Microsoft.Office.Interop.Excel;(?屬性里的嵌入互操作類型改為Fasle)

2、Default10.aspx

? ?<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default10.aspx.cs" Inherits="Default10" %> ?
? ?
<!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"> ?
? ? ? ?
<div> ?
? ? ? ? ?
<asp:Button ID="ExportToExcel" runat="server" Text="導出Excel" ?
? ? ? ? ? ? ? ?onclick
="ExportToExcel_Click" /> ?
? ? ? ?
</div> ?
? ? ? ?
</form> ?
? ?
</body> ?
? ?
</html> ?

3、Default10.aspx.cs

? ?using System; ?
? ?
using System.Collections.Generic; ?
? ?
using System.Linq; ?
? ?
using System.Web; ?
? ?
using System.Web.UI; ?
? ?
using System.Web.UI.WebControls; ?
? ?
using Excel = Microsoft.Office.Interop.Excel; //添加引用 ?
? ?public partial class Default10 : System.Web.UI.Page ?
? ?{ ?
? ? ? ?
protected void Page_Load(object sender, EventArgs e) ?
? ? ? ?{ ?
? ? ? ?} ?
? ? ? ?
protected void ExportToExcel_Click(object sender, EventArgs e) ?
? ? ? ?{ ?
? ? ? ? ? ?Excel.Application excel1
= new Excel.Application(); ?
? ? ? ? ? ?excel1.DisplayAlerts
= false; ?
? ? ? ? ? ?Excel.Workbook workbook1
= excel1.Workbooks.Add(Type.Missing); ?
? ? ? ? ? ?excel1.Visible
= false; ?
? ? ? ? ? ?Excel.Worksheet worksheet1
= (Excel.Worksheet)workbook1.Worksheets["sheet1"]; ?
? ? ? ? ? ?
//表頭 ? ?
? ? ? ? ? ?worksheet1.Cells[1, 1] = "姓名"; ?//Excel里從第1行,第1列計算 ? ?
? ? ? ? ? ?worksheet1.Cells[1, 2] = "性別"; ?
? ? ? ? ? ?worksheet1.Cells[
1, 3] = "聯系電話"; ?
? ? ? ? ? ?System.Data.DataTable dt
= GetTestData(100); ?
? ? ? ? ? ?
for (int i = 0; i < dt.Rows.Count; i++) ?
? ? ? ? ? ?{ ?
? ? ? ? ? ? ? ?
for (int j = 0; j < dt.Columns.Count; j++) ?
? ? ? ? ? ? ? ? ? ?worksheet1.Cells[i
+ 2, j + 1] = dt.Rows[i][j].ToString(); ?
? ? ? ? ? ?} ?
? ? ? ? ? ?
string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls"; ?
? ? ? ? ? ?
string filePath = Server.MapPath("~/" + fileName); ?
? ? ? ? ? ?workbook1.SaveAs(filePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); ?
? ? ? ? ? ?excel1.Workbooks.Close(); ?
? ? ? ? ? ?excel1.Quit(); ?
? ? ? ? ? ?
int generation = GC.GetGeneration(excel1); ?
? ? ? ? ? ?System.Runtime.InteropServices.Marshal.ReleaseComObject(excel1); ?
? ? ? ? ? ?excel1
= null; ?
? ? ? ? ? ?GC.Collect(generation); ?
? ? ? ? ? ?
//打開要下載的文件,并把該文件存放在FileStream中 ? ?
? ? ? ? ? ?System.IO.FileStream Reader = System.IO.File.OpenRead(filePath); ?
? ? ? ? ? ?
//文件傳送的剩余字節數:初始值為文件的總大小 ? ?
? ? ? ? ? ?long Length = Reader.Length; ?
? ? ? ? ? ?HttpContext.Current.Response.Buffer
= false; ?
? ? ? ? ? ?HttpContext.Current.Response.AddHeader(
"Connection", "Keep-Alive"); ?
? ? ? ? ? ?HttpContext.Current.Response.ContentType
= "application/octet-stream"; ?
? ? ? ? ? ?HttpContext.Current.Response.AddHeader(
"Content-Disposition", "attachment; filename=" + fileName); ?
? ? ? ? ? ?HttpContext.Current.Response.AddHeader(
"Content-Length", Length.ToString()); ?
? ? ? ? ? ?
byte[] Buffer = new Byte[10000]; ? ?//存放欲發送數據的緩沖區 ? ?
? ? ? ? ? ?int ByteToRead; ? ? ? ? ? ? ? ? ? ? //每次實際讀取的字節數 ? ?
? ? ? ? ? ?while (Length > 0) ?
? ? ? ? ? ?{ ?
? ? ? ? ? ? ? ?
//剩余字節數不為零,繼續傳送 ? ?
? ? ? ? ? ? ? ?if (Response.IsClientConnected) ?
? ? ? ? ? ? ? ?{ ?
? ? ? ? ? ? ? ? ? ?
//客戶端瀏覽器還打開著,繼續傳送 ? ?
? ? ? ? ? ? ? ? ? ?ByteToRead = Reader.Read(Buffer, 0, 10000); //往緩沖區讀入數據 ? ?
? ? ? ? ? ? ? ? ? ?HttpContext.Current.Response.OutputStream.Write(Buffer, 0, ByteToRead); //把緩沖區的數據寫入客戶端瀏覽器 ? ?
? ? ? ? ? ? ? ? ? ?HttpContext.Current.Response.Flush(); ? //立即寫入客戶端 ? ?
? ? ? ? ? ? ? ? ? ?Length -= ByteToRead; ? //剩余字節數減少 ? ?
? ? ? ? ? ? ? ?} ?
? ? ? ? ? ? ? ?
else ?
? ? ? ? ? ? ? ?{ ?
? ? ? ? ? ? ? ? ? ?
//客戶端瀏覽器已經斷開,阻止繼續循環 ? ?
? ? ? ? ? ? ? ? ? ?Length = -1; ?
? ? ? ? ? ? ? ?} ?
? ? ? ? ? ?} ?
? ? ? ? ? ?
//關閉該文件 ? ?
? ? ? ? ? ?Reader.Close(); ?
? ? ? ? ? ?
if (System.IO.File.Exists(filePath)) ?
? ? ? ? ? ? ? ?System.IO.File.Delete(filePath); ?
? ? ? ?} ?
? ? ? ?System.Data.DataTable GetTestData(
int num) //測試數據 ? ?
? ? ? ?{ ?
? ? ? ? ? ?System.Data.DataTable dt
= new System.Data.DataTable(); ?
? ? ? ? ? ?System.Data.DataRow dr; ?
? ? ? ? ? ?dt.Columns.Add(
new System.Data.DataColumn("ContactName", typeof(String))); ?
? ? ? ? ? ?dt.Columns.Add(
new System.Data.DataColumn("ContactSex", typeof(String))); ?
? ? ? ? ? ?dt.Columns.Add(
new System.Data.DataColumn("ContactPhone", typeof(String))); ?
? ? ? ? ? ?
for (int i = 0; i < num; i++) ?
? ? ? ? ? ?{ ?
? ? ? ? ? ? ? ?Random rnd
= new Random(Environment.TickCount * i); ?
? ? ? ? ? ? ? ?dr
= dt.NewRow(); ?
? ? ? ? ? ? ? ?dr[
0] = "姓名" + rnd.Next(1, num); ?
? ? ? ? ? ? ? ?dr[
1] = rnd.Next(1, num) < num / 2 ? "" : ""; ?
? ? ? ? ? ? ? ?dr[
2] = rnd.Next(1000000, 99999999); ?
? ? ? ? ? ? ? ?dt.Rows.Add(dr); ?
? ? ? ? ? ?} ?
? ? ? ? ? ?
return dt; ?
? ? ? ?} ?
? ?} ?

另一種利用Excel模板生成Excel方法如下:

? ?private void ExportToExcel(DataTable dt, string fileName) ?
? ? ? ? ?{ ?
? ? ? ? ? ? ?
//轉換為物理路徑 ?
? ? ? ? ? ? ?string newFileName = HttpContext.Current.Server.MapPath("~/" + fileName); ?
? ? ? ? ? ? ?
//根據模板正式生成該Excel文件 ?
? ? ? ? ? ? ?File.Copy(HttpContext.Current.Server.MapPath("~/ContactTemplate.xls"), newFileName, true); ?
? ? ? ? ? ? ?
//建立指向該Excel文件的數據庫連接 ?
? ? ? ? ? ? ?string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + newFileName + ";Extended Properties='Excel 8.0;HDR=yes;IMEX=2'"; ?
? ? ? ? ? ? ?OleDbConnection Conn
= new OleDbConnection(strConn); ?
? ? ? ? ? ? ?
//打開連接,為操作該文件做準備 ?
? ? ? ? ? ? ?Conn.Open(); ?
? ? ? ? ? ? ?OleDbCommand Cmd
= new OleDbCommand("", Conn); ?
? ? ? ? ? ? ?
foreach (DataRow DR in dt.Rows) ?
? ? ? ? ? ? ?{ ?
? ? ? ? ? ? ? ? ?
string XSqlString = "insert into [Sheet1$]"; ?
? ? ? ? ? ? ? ? ?XSqlString
+= "([姓名],[性別],[聯系電話]) values("; ?
? ? ? ? ? ? ? ? ?XSqlString
+= "'" + DR["ContactName"] + "',"; ?
? ? ? ? ? ? ? ? ?XSqlString
+= "'" + (DR["ContactSex"].ToString() == "1" ? "" : "") + "',"; ?
? ? ? ? ? ? ? ? ?XSqlString
+= "'" + DR["ContactPhone"] + "')"; ?
? ? ? ? ? ? ? ? ?Cmd.CommandText
= XSqlString; ?
? ? ? ? ? ? ? ? ?Cmd.ExecuteNonQuery(); ?
? ? ? ? ? ? ?} ?
? ? ? ? ? ? ?
//操作結束,關閉連接 ?
? ? ? ? ? ? ?Conn.Close(); ?
? ? ? ? ? ? ?
//打開要下載的文件,并把該文件存放在FileStream中 ?
? ? ? ? ? ? ?System.IO.FileStream Reader = System.IO.File.OpenRead(newFileName); ?
? ? ? ? ? ? ?
//文件傳送的剩余字節數:初始值為文件的總大小 ?
? ? ? ? ? ? ?long Length = Reader.Length; ?
? ? ? ? ? ? ?HttpContext.Current.Response.Buffer
= false; ?
? ? ? ? ? ? ?HttpContext.Current.Response.AddHeader(
"Connection", "Keep-Alive"); ?
? ? ? ? ? ? ?HttpContext.Current.Response.ContentType
= "application/octet-stream"; ?
? ? ? ? ? ? ?HttpContext.Current.Response.Charset
= "utf-8"; ?
? ? ? ? ? ? ?HttpContext.Current.Response.AddHeader(
"Content-Disposition", "attachment; filename=" + fileName); ?
? ? ? ? ? ? ?HttpContext.Current.Response.AddHeader(
"Content-Length", Length.ToString()); ?
? ? ? ? ? ? ?
byte[] Buffer = new Byte[10000]; ? ? ?//存放欲發送數據的緩沖區 ?
? ? ? ? ? ? ?int ByteToRead; ? ? ? ? ? ? ? ? ? ? ? ? ? //每次實際讀取的字節數 ?
? ? ? ? ? ? ?while (Length > 0) ?
? ? ? ? ? ? ?{ ?
? ? ? ? ? ? ? ? ?
//剩余字節數不為零,繼續傳送 ?
? ? ? ? ? ? ? ? ?if (Response.IsClientConnected) ?
? ? ? ? ? ? ? ? ?{ ?
? ? ? ? ? ? ? ? ? ? ?
//客戶端瀏覽器還打開著,繼續傳送 ?
? ? ? ? ? ? ? ? ? ? ?ByteToRead = Reader.Read(Buffer, 0, 10000); ? ? ? ? ? ? ? ? ? //往緩沖區讀入數據 ?
? ? ? ? ? ? ? ? ? ? ?HttpContext.Current.Response.OutputStream.Write(Buffer, 0, ByteToRead); ? //把緩沖區的數據寫入客戶端瀏覽器 ?
? ? ? ? ? ? ? ? ? ? ?HttpContext.Current.Response.Flush(); ? ? ? ? //立即寫入客戶端 ?
? ? ? ? ? ? ? ? ? ? ?Length -= ByteToRead; ? ? //剩余字節數減少 ?
? ? ? ? ? ? ? ? ?} ?
? ? ? ? ? ? ? ? ?
else ?
? ? ? ? ? ? ? ? ?{ ?
? ? ? ? ? ? ? ? ? ? ?
//客戶端瀏覽器已經斷開,阻止繼續循環 ?
? ? ? ? ? ? ? ? ? ? ?Length = -1; ?
? ? ? ? ? ? ? ? ?} ?
? ? ? ? ? ? ?} ?
? ? ? ? ? ? ?
//關閉該文件 ?
? ? ? ? ? ? ?Reader.Close(); ?
? ? ? ? ? ? ?
//刪除該Excel文件 ?
? ? ? ? ? ? ?if (File.Exists(newFileName)) ?
? ? ? ? ? ? ? ? ?File.Delete(newFileName); ?
? ? ? ? ?} ? ?

---------------------------------------------------------------------------

2010-8-26? 備注:

在項目中使用第2種方法時,出現"操作必須使用一個可更新的查詢"的錯誤提示 ,原因是項目采用TFS管理,使Excel文件屬性是只讀的,解決方法是去掉只讀屬性:

?File.Copy(HttpContext.Current.Server.MapPath("~/Views/ActivityAdmin/ContactTemplate.xls"), newFileName, true);

在上面代碼的下面加上:


?FileInfo f = new FileInfo(newFileName);
? if (f.Attributes.ToString().IndexOf("ReadOnly") != -1)
? {
??????? f.Attributes = FileAttributes.Normal;
?}

---------------------------------------------------------------------------

17:11 2010-12-23 備注:

用企業庫讀取Excel:


web.config配置:


<!--test.xls放在App_Data目錄下-->
<!--HDR=yes;IMEX=1表示:第一行不作為數據返回,且以文本方式讀取-->
<add name="testXls" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;data source=|DataDirectory|test.xls;Extended Properties='Excel 8.0;HDR=yes;IMEX=1'" ? providerName="System.Data.OleDb" />


*.aspx.cs代碼:

using Microsoft.Practices.EnterpriseLibrary.Data;

Database db
= DatabaseFactory.CreateDatabase("testXls");
//[B0201$A2:C33]表示讀取表B0201$的區域范圍A2:C33
DataTable dt = db.ExecuteDataSet(CommandType.Text, "select * from [B0201$A2:C33]").Tables[0];


另一種不錯方法:

使用HTML,CSS快速導出數據到Excel

http://www.cnblogs.com/ruinet/archive/2009/10/17/1585320.html

稍微改了下

?

public static void CreateExcel(string strTable, string fileName)
? ? ? ?{
? ? ? ? ? ?
string HEADER = "<html xmlns:x=\"urn:schemas-microsoft-com:office:excel\">" +
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
"<meta http-equiv=Content-Type content=\"text/html; charset=\"gb2312\">" +
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
"<head>" +
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
"<!--[if gte mso 9]><xml>" +
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
"<x:ExcelWorkbook>" +
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
"<x:ExcelWorksheets>" +
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
"<x:ExcelWorksheet>" +
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
"<x:Name>Sheet1</x:Name>" +
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
"<x:WorksheetOptions>" +
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
"<x:Print>" +
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
"<x:ValidPrinterInfo />" +
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
"</x:Print>" +
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
"</x:WorksheetOptions>" +
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
"</x:ExcelWorksheet>" +
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
"</x:ExcelWorksheets>" +
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
"</x:ExcelWorkbook>" +
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
"</xml>" +
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
"<![endif]-->";

? ? ? ? ? ?System.Web.HttpContext.Current.Response.ContentEncoding
= System.Text.Encoding.GetEncoding("GB2312");
? ? ? ? ? ?System.Web.HttpContext.Current.Response.AppendHeader(
"Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
? ? ? ? ? ?System.Web.HttpContext.Current.Response.ContentType
= "ms-excel/application";


? ? ? ? ? ?StringBuilder sbHtml
= new StringBuilder();
? ? ? ? ? ?sbHtml.AppendFormat(
@"{0}</head>
? ? ? ? ? ? ? ? ? ? ? ? <body>{1}</body>
? ? ? ? ? ? ? ? ? ? ? ? </html>
", HEADER, strTable);

? ? ? ? ? ?System.Web.HttpContext.Current.Response.Write(sbHtml.ToString());
? ? ? ? ? ?System.Web.HttpContext.Current.Response.Flush();
? ? ? ? ? ?System.Web.HttpContext.Current.Response.Clear();
? ? ? ? ? ?System.Web.HttpContext.Current.Response.End();
? ? ? ?}


轉載于:https://my.oschina.net/bv10000/blog/190999

總結

以上是生活随笔為你收集整理的.net导出Excel的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。