62,046
社区成员
发帖
与我相关
我的任务
分享
/// <summary>
/// DataTable通过流导出Excel
/// </summary>
/// <param name="ds">数据源DataSet或者DataTable</param>
/// <param name="columns">DataTable中列对应的列名(可以是中文),若为null则取DataTable中的字段名</param>
/// <param name="fileName">保存文件名(例如:a.xls)</param>
/// <returns></returns>
public bool StreamExport(DataTable dt, ArrayList columns, string fileName, System.Web.UI.Page pages)
{
if (dt.Rows.Count > 65535) //总行数大于Excel的行数
{
throw new Exception("预导出的数据总行数大于excel的行数");
}
if (string.IsNullOrEmpty(fileName)) return false;
StringBuilder content = new StringBuilder();
StringBuilder strtitle = new StringBuilder();
content.Append("<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:excel' xmlns='http://www.w3.org/TR/REC-html40'>");
content.Append("<head><title></title><meta http-equiv='Content-Type' content=\"text/html; charset=gb2312\">");
//注意:[if gte mso 9]到[endif]之间的代码,用于显示Excel的网格线,若不想显示Excel的网格线,可以去掉此代码
content.Append("<!--[if gte mso 9]>");
content.Append("<xml>");
content.Append(" <x:ExcelWorkbook>");
content.Append(" <x:ExcelWorksheets>");
content.Append(" <x:ExcelWorksheet>");
content.Append(" <x:Name>Sheet1</x:Name>");
content.Append(" <x:WorksheetOptions>");
content.Append(" <x:Print>");
content.Append(" <x:ValidPrinterInfo />");
content.Append(" </x:Print>");
content.Append(" </x:WorksheetOptions>");
content.Append(" </x:ExcelWorksheet>");
content.Append(" </x:ExcelWorksheets>");
content.Append("</x:ExcelWorkbook>");
content.Append("</xml>");
content.Append("<![endif]-->");
content.Append("</head><body><table style='border-collapse:collapse;table-layout:fixed;'><tr>");
if (columns != null)
{
for (int i = 0; i < columns.Count; i++)
{
if (columns[i] != null && columns[i] != "")
{
content.Append("<td><b>" + columns[i] + "</b></td>");
}
else
{
content.Append("<td><b>" + dt.Columns[i].ColumnName + "</b></td>");
}
}
}
else
{
for (int j = 0; j < dt.Columns.Count; j++)
{
content.Append("<td><b>" + dt.Columns[j].ColumnName + "</b></td>");
}
}
content.Append("</tr>\n");
for (int j = 0; j < dt.Rows.Count; j++)
{
content.Append("<tr>");
for (int k = 0; k < dt.Columns.Count; k++)
{
object obj = dt.Rows[j][k];
Type type = obj.GetType();
if (type.Name == "Int32" || type.Name == "Single" || type.Name == "Double" || type.Name == "Decimal")
{
double d = obj == DBNull.Value ? 0.0d : Convert.ToDouble(obj);
if (type.Name == "Int32" || (d - Math.Truncate(d) == 0))
content.AppendFormat("<td style='vnd.ms-excel.numberformat:#,##0'>{0}</td>", obj);
else
content.AppendFormat("<td style='vnd.ms-excel.numberformat:#,##0.00'>{0}</td>", obj);
}
else
content.AppendFormat("<td style='vnd.ms-excel.numberformat:@'>{0}</td>", obj);
}
content.Append("</tr>\n");
}
content.Append("</table></body></html>");
content.Replace(" ", "");
pages.Response.Clear();
pages.Response.Buffer = true;
pages.Response.ContentType = "application/ms-excel"; //"application/ms-excel";
pages.Response.Charset = "UTF-8";
pages.Response.ContentEncoding = System.Text.Encoding.UTF7;
fileName = System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8);
pages.Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
pages.Response.Write(content.ToString());
//pages.Response.End(); //注意,若使用此代码结束响应可能会出现“由于代码已经过优化或者本机框架位于调用堆栈之上,无法计算表达式的值。”的异常。
HttpContext.Current.ApplicationInstance.CompleteRequest(); //用此行代码代替上一行代码,则不会出现上面所说的异常。
return true;
}
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server" id="Head1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="File1" type="file" runat="server" />
<asp:Button ID="Button1" runat="server" Text="导入" OnClick="btnUpload_Click" /><br />
<asp:Button ID="cmdOpen" runat="server" Text="在线打开" CommandName="open" OnCommand="Button_Click" />
<asp:Button ID="cmdSave"
runat="server" Text="本地保存" CommandName="save" OnCommand="Button_Click" />
<asp:DropDownList ID="listType" runat="server">
<asp:ListItem Value="excel">Excel</asp:ListItem>
<asp:ListItem Value="word">Word</asp:ListItem>
</asp:DropDownList>
<br />
数据源:
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</div>
</form>
</body>
</html>
using System;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.Sql;
using System.Reflection;
using System.IO;
using Microsoft.Office.Interop.Excel;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//FillGridView();
}
/**/
/// <summary>
/// 实现excel中的数据导入
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnUpload_Click(object sender, EventArgs e)
{
if (File1.Value == string.Empty || File1.Value == "")
{
Response.Write("<Script>alert('选择路径');</Script>");
}
else
{
FileInfo file = new FileInfo(File1.PostedFile.FileName.ToString());
string sConnectionString;
string extension = file.Extension;
switch (extension)
{
case ".xls":
sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + file + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
break;
case ".xlsx":
sConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + file + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'";
break;
default:
sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + file + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
break;
}
OleDbConnection objConn = new OleDbConnection(sConnectionString);
objConn.Open();
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter("select * from [Sheet1$]", objConn);
DataSet objDataset1 = new DataSet();
objAdapter1.Fill(objDataset1, "XLData");
GridView1.DataSource = objDataset1.Tables[0];
GridView1.DataBind();
objConn.Close();
}
}
private void OutPut(string fileType, string strType)
{
Response.Clear();
Response.Buffer = true;
Response.Charset = "GB2312";
Response.AppendHeader("Content-Disposition", fileType);
Response.ContentType = strType;
this.EnableViewState = false;
System.IO.StringWriter swOut = new System.IO.StringWriter();
HtmlTextWriter hTw = new HtmlTextWriter(swOut);
GridView1.RenderControl(hTw);
Response.Write(swOut.ToString());
Response.End();
}
protected void Button_Click(object sender, CommandEventArgs e)
{
switch (e.CommandName)
{
case "save":
switch (listType.SelectedValue)
{
case "excel":
OutPut("attachment;filename=out.xls", "application/ms-excel");
break;
case "word":
OutPut("attachment;filename=out.doc", "application/ms-word");
break;
}
break;
case "open":
switch (listType.SelectedValue)
{
case "excel":
OutPut("online;filename=out.xls", "application/ms-excel");
break;
case "word":
OutPut("online;filename=out.doc", "application/ms-word");
break;
}
break;
}
}
public override void VerifyRenderingInServerForm(Control control)
{
}
}