Excel导出的几种方式

时间:2021-12-07 12:44:32

1、html

前台html与js代码(文件:ExportExcelByHtml.aspx):

 <html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:LinkButton runat="server" OnClientClick="return tiggerAlert();" OnClick="Button1_Click">Matt Cheng</asp:LinkButton>
<br />
<asp:HiddenField ID="ExportField" runat="server" />
</div>
</form>
</body>
</html> <script type="text/javascript">
function tiggerAlert() {
var html = "<html><head><style type=\"text/css\">#tt{color:green;}</style></head><body>"
+ "<div>"
+ "<table>"
+ "<tr><th style='color:red;'>cheng</th><th>liu</th></tr>"
+ "<tr><td id='tt'>7845</td><td>666</td></tr>"
+ "</table>"
+ "</div>"
+ "</body><html>";
document.getElementById("ExportField").value = escape(html); return true;
}
</script>

注:注意控件LinkButton点击事件的用法,OnClientClick为前台事件(js),OnClick为后台事件(C#),当用户点击按钮,先响应OnClientClick,若OnClientClick的返回结果为true,则执行OnClick,否则不执行。

后台C#代码(ExportExcelByHtml.aspx.cs)

   public partial class ClientClick : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
} protected void Button1_Click(object sender, EventArgs e)
{
string fileName = HttpUtility.UrlEncode("想你的夜") + DateTime.Now.ToString("yyyyMMdd") + ".xls";
Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
Response.ContentType = "application/vnd.ms-excel";
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
oHtmlTextWriter.Write(HttpUtility.UrlDecode(this.ExportField.Value));
Response.Write(oStringWriter.ToString());
//Response.Write(HttpUtility.UrlDecode(this.ExportField.Value));
Response.End();
}
}

注:13-16行的效果和17行相同。但通常采用前一种方式,原因未知。。。。

html导出excel的特点:能够通过样式(内部样式表与内联样式)设置excel的格式。

 2、数据源

前台html与js代码(文件:ExportExcelByOle.aspx):

 <html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function exportExcel() {
document.getElementById("iframe0").src = "ttttt.aspx?timeTick=" + ((new Date()) - (new Date(1, 1, 1)));
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="button" value="button" onclick="exportExcel()" />
<iframe id="iframe0" style="display:none;" src="" />
</div>
</form>
</body>
</html>

注:将js代码(即<script>标签)放到html后,在onclick中的exportExcel未定义(undefined),原因未知。。。。

web.config配置:

<httpHandlers>
<add path="ttttt.aspx" verb="*" type="ExcelExportTest.ExcelExportHandler"/>
</httpHandlers>

注:iis对http请求的响应方式详见Http Handler介绍

后台C#代码(ExcelExportHandler.cs):

 public class ExcelExportHandler : IHttpHandler
{
private HttpContext context; public bool IsReusable { get { return true; } } public void ProcessRequest(HttpContext context)
{
this.context = context; DataRow row;
DataSet ds = new DataSet();
DataTable dt = new DataTable();
dt.TableName = "table";
dt.Columns.Add("cheng");
dt.Columns.Add("liu");
dt.Columns.Add("杨");
row = dt.NewRow();
row["cheng"] = "";
row["liu"] = "tttt";
row["杨"] = " 面包";
dt.Rows.Add(row);
row = dt.NewRow();
row["cheng"] = "tt";
row["liu"] = "ttpppptt";
row["杨"] = "可乐";
dt.Rows.Add(row);
ds.Tables.Add(dt); string rootPath = AppDomain.CurrentDomain.BaseDirectory + "files\\";
if (!Directory.Exists(rootPath))
Directory.CreateDirectory(rootPath);
string filePath = rootPath + DateTime.Now.Ticks.ToString() + ".xls";
//File.Create(filePath);
DataSetToExcel(ds, filePath);
WriteExcelFile(filePath, "成功");
if (File.Exists(filePath))
{
FileInfo fInfo = new FileInfo(filePath);
fInfo.Attributes = FileAttributes.Normal;
File.Delete(filePath);
}
} private void DataSetToExcel(DataSet ds, string filePath)
{
using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=\"Excel 8.0;HDR=yes;IMEX=0\";"))
{
if (conn.State != ConnectionState.Open)
conn.Open(); foreach (DataTable dt in ds.Tables)
{
OleDbCommand cmdCreateTable = new OleDbCommand("create table [table] ([cheng] varchar, [liu] varchar, [杨] varchar)", conn);
OleDbCommand cmdInsertRow = new OleDbCommand("insert into [table] ([cheng], [liu], [杨]) values(?, ?, ?)", conn);
cmdCreateTable.ExecuteNonQuery(); foreach (DataColumn dc in dt.Columns)
{
cmdInsertRow.Parameters.Add(new OleDbParameter(dc.ColumnName, ""));
}
foreach (DataRow dr in dt.Rows)
{
foreach (DataColumn dc in dt.Columns)
{
cmdInsertRow.Parameters[dc.ColumnName].Value = dr[dc.ColumnName];
}
cmdInsertRow.ExecuteNonQuery();
}
}
}
} private void WriteExcelFile(string filePath, string fileName)
{
if (File.Exists(filePath))
{
FileStream fStream = new FileStream(filePath, FileMode.Open);
try
{
context.Response.Clear();
context.Response.ContentType = "application/vnd.ms-excel";
context.Response.AppendHeader("Content-Disposition", "attachment;filename=" + context.Server.UrlEncode(fileName) + ".xls");
long len = fStream.Length;
long lCount = ;
int bLen = ;
byte[] buffer = new byte[bLen];
while (lCount < len)
{
lCount += fStream.Read(buffer, , bLen);
context.Response.BinaryWrite(buffer);
context.Response.Flush();
}
}
finally
{
fStream.Close();
}
}
}
}

注:OleDbConnection 连接数据源时自动创建文件,写数据的cmd语句和SQL相同。

数据源导出excel特点:可以在一个excel文件中写多个表格(sheet),但格式目前没有找到控制方法

3、Xml

xml的导出的调用方式与数据源导出类似,通过HttpHandler方式实现。

后台代码(ExcelExportByXml.cs):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Text;
using System.Xml; namespace FileExport
{
public class ExcelExportByXml
{
private const string excelTemplate = "excelTable.xml";
private HttpContext context; public ExcelExportByXml(HttpContext httpContext)
{
this.context = httpContext;
} public void ExportExcel(object data)
{
List<DataEntity> list = data as List<DataEntity>;
string moduleFile = GetExcelModule(); StringBuilder tableString = new StringBuilder("<Column ss:Width=\"90\"/>");
tableString.Append("<Column ss:Width=\"90\"/>");
tableString.Append("<Column ss:Width=\"90\"/>"); string[] headers = { "Data1", "Data2", "Data3" };
SetTableHeader(tableString, headers); foreach (DataEntity info in list)
{
tableString.Append("<Row>");
tableString.Append("<Cell ss:StyleID=\"s65\"><Data ss:Type=\"String\">" + info.Data1 + "</Data></Cell>");
tableString.Append("<Cell ss:StyleID=\"s66\"><Data ss:Type=\"String\">" + info.Data2 + "</Data></Cell>");
tableString.Append("<Cell ss:StyleID=\"s65\"><Data ss:Type=\"String\">" + info.Data3 + "</Data></Cell>");
tableString.Append("</Row>");
} moduleFile = String.Format(moduleFile, "", "爱你一万年", tableString.ToString());
WriteExcelFile(moduleFile, DateTime.Now.Ticks.ToString());
} private string GetExcelModule()
{
string res = "";
string filePath = AppDomain.CurrentDomain.BaseDirectory + excelTemplate;
using (StreamReader sr = new StreamReader(filePath))
{
res = sr.ReadToEnd();
sr.Close();
}
return res;
} private void SetTableHeader(StringBuilder tableString, string[] headers)
{
if (tableString != null && headers.Length > )
{
tableString.Append("<Row ss:Index=\"2\">");
foreach (string header in headers)
{
tableString.Append("<Cell ss:StyleID=\"s63\"><Data ss:Type=\"String\">");
tableString.Append(header);
tableString.Append("</Data></Cell>");
}
tableString.Append("</Row>");
}
} private void WriteExcelFile(string fileString, string fileName)
{
if (!String.IsNullOrEmpty(fileString))
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(fileString);
XmlWriterSettings xmlSettings = new XmlWriterSettings();
xmlSettings.Indent = true;
xmlSettings.Encoding = Encoding.UTF8;
xmlSettings.OmitXmlDeclaration = false;
MemoryStream ms = new MemoryStream();
using (XmlWriter xw = XmlWriter.Create(ms, xmlSettings))
{
doc.WriteTo(xw);
xw.Close();
}
WriteFile(ms, fileName);
}
} private void WriteFile(MemoryStream ms, string fileName)
{
try
{
this.context.Response.ContentType = "application/vnd.ms-excel";
this.context.Response.AppendHeader("Content-Disposition", "attachment;filename=" + this.context.Server.UrlEncode(fileName) + ".xls;charset=utf8");
ms.Position = ;
int size = *; // 10K
byte[] buffer = new byte[size];
while (ms.Read(buffer, , size) > )
{
this.context.Response.BinaryWrite(buffer);
this.context.Response.OutputStream.Flush();
} }
catch (Exception ex)
{
}
finally
{
ms.Close();
}
}
} class DataEntity
{
public string Data1 { set; get; }
public string Data2 { set; get; }
public string Data3 { set; get; }
}
}

模板(excelTable.xml)

<?xml version="1.0" encoding="utf-8" ?>
<?mso-application progid="Excel.Sheet"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:html="http://www.w3.org/TR/REC-html40">
<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">
<Title>{0}</Title>
<LastAuthor>Wind</LastAuthor>
<Created>2013-11-22T06:50:15Z</Created>
<LastSaved>2013-11-22T06:50:15Z</LastSaved>
<Version>12.00</Version>
</DocumentProperties>
<ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">
<WindowHeight>10005</WindowHeight>
<WindowWidth>10005</WindowWidth>
<WindowTopX>120</WindowTopX>
<WindowTopY>135</WindowTopY>
<ProtectStructure>False</ProtectStructure>
<ProtectWindows>False</ProtectWindows>
</ExcelWorkbook>
<Styles>
<Style ss:ID="s63">
<Alignment ss:Horizontal="Center" ss:Vertical="Center" ss:WrapText="1"/>
<Borders>
<Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1"
ss:Color="#000000"/>
<Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1"
ss:Color="#000000"/>
<Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1"
ss:Color="#000000"/>
<Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1"
ss:Color="#000000"/>
</Borders>
<Font ss:FontName="宋体" x:CharSet="134" ss:Color="#000000" ss:Bold="1"/>
</Style>
<Style ss:ID="s64">
<Alignment ss:Horizontal="Right" ss:Vertical="Center" ss:WrapText="1"/>
<Borders>
<Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1"
ss:Color="#000000"/>
<Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1"
ss:Color="#000000"/>
<Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1"
ss:Color="#000000"/>
<Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1"
ss:Color="#000000"/>
</Borders>
<Font ss:FontName="宋体" x:CharSet="134" ss:Color="#000000"/>
</Style>
<Style ss:ID="s65">
<Alignment ss:Horizontal="Center" ss:Vertical="Center" ss:WrapText="1"/>
<Borders>
<Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1"
ss:Color="#000000"/>
<Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1"
ss:Color="#000000"/>
<Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1"
ss:Color="#000000"/>
<Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1"
ss:Color="#000000"/>
</Borders>
<Font ss:FontName="宋体" x:CharSet="134" ss:Color="#000000"/>
</Style>
<Style ss:ID="s66">
<Alignment ss:Horizontal="Left" ss:Vertical="Center" ss:WrapText="1"/>
<Borders>
<Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1"
ss:Color="#000000"/>
<Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1"
ss:Color="#000000"/>
<Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1"
ss:Color="#000000"/>
<Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1"
ss:Color="#000000"/>
</Borders>
<Font ss:FontName="宋体" x:CharSet="134" ss:Color="#000000"/>
</Style>
</Styles>
<Worksheet ss:Name="{1}">
<Table x:FullColumns="1"
x:FullRows="1" ss:DefaultColumnWidth="54" ss:DefaultRowHeight="13.5">{2}</Table>
<WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
<Print>
<ValidPrinterInfo/>
<VerticalResolution>0</VerticalResolution>
</Print>
<Selected/>
<Panes>
<Pane>
<Number>3</Number>
<RangeSelection>R1C1:R1C10</RangeSelection>
</Pane>
</Panes>
<ProtectObjects>False</ProtectObjects>
<ProtectScenarios>False</ProtectScenarios>
</WorksheetOptions>
</Worksheet>
</Workbook>

调用方法(在HttpHandler中):

List<DataEntity> list = new List<DataEntity>();
DataEntity de1 = new DataEntity { Data1 = "pp", Data2 = "rrr", Data3 = "" };
DataEntity de2 = new DataEntity { Data1 = "pp", Data2 = "rrr", Data3 = "" };
list.Add(de1);
list.Add(de2);
ExcelExportByXml excelExport = new ExcelExportByXml(this.context);
excelExport.ExportExcel(list);

该方法的优点:可以充分控制excel中表格的样式。

注:该方法使用Office Open XML技术,目前没有找到较好的参考文档,为了查找要达到的效果对应的标签,可以新建excel文档,编辑相应的效果,之后再另存为xml格式的文本,查看对应的标签即可。

4、GridView

该方法同样使用HttpHandler,代码结构与数据源相同。

    // 使用GridView
if (ds.Tables[].Rows.Count > )
{
//当前对话
System.Web.HttpContext curContext = System.Web.HttpContext.Current;
//IO用于导出并返回excel文件
System.IO.StringWriter strWriter = null;
System.Web.UI.HtmlTextWriter htmlWriter = null; //设置编码和附件格式
//System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8)作用是方式中文文件名乱码
curContext.Response.AddHeader("content-disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode("定投排行榜", System.Text.Encoding.UTF8) + ".xls");
curContext.Response.ContentType = "application nd.ms-excel";
curContext.Response.ContentEncoding = System.Text.Encoding.UTF8;
curContext.Response.Charset = "GB2312"; //导出Excel文件
strWriter = new System.IO.StringWriter();
htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter); //为了解决dgData中可能进行了分页的情况,需要重新定义一个无分页的GridView
GridView gvExport = new GridView();
gvExport.DataSource = ds.Tables[].DefaultView;
gvExport.AllowPaging = false;
gvExport.DataBind(); //下载到客户端
gvExport.RenderControl(htmlWriter);
curContext.Response.Write(strWriter.ToString());
curContext.Response.End();
}

该方法的本质与html相同,即生成html代码并输出到前台。

优点:html代码通过控件自动生成,使用简单。

读取excel的一种简单方式:

using System;
using System.Data;
using System.Data.OleDb; namespace ExcelReading
{
class Program
{
static void Main(string[] args)
{
DataSet ds = GetDateSet(@"C:\Users\jcheng.matt\Desktop\test.xlsx");
DataTable dt = ds.Tables[];
} public static DataSet GetDateSet(string filePath)
{
string fileType = System.IO.Path.GetExtension(filePath);
if (string.IsNullOrEmpty(fileType))
{
return null;
} string connStr = string.Empty;
if (fileType == ".xls")
connStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filePath + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
else
connStr = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + filePath + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\""; OleDbConnection conn = null;
OleDbDataAdapter adapter = new OleDbDataAdapter();
DataSet ds = new DataSet();
try
{
// 初始化连接,并打开
conn = new OleDbConnection(connStr);
conn.Open(); // 获取数据源的表定义元数据
DataTable dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" }); string sheetName = string.Empty;
string sql = "Select * FROM [{0}]";
for (int i = ; i < dtSheetName.Rows.Count; i++)
{
sheetName = (string)dtSheetName.Rows[i]["TABLE_NAME"];
adapter.SelectCommand = new OleDbCommand(String.Format(sql, sheetName), conn);
DataSet dsItem = new DataSet();
adapter.Fill(dsItem, sheetName);
ds.Tables.Add(dsItem.Tables[].Copy());
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
// 关闭连接
if (conn.State == ConnectionState.Open)
{
conn.Close();
adapter.Dispose();
conn.Dispose();
}
}
return ds;
}
}
}

Excel导出的几种方式的更多相关文章

  1. &period;NET环境下导出Excel表格的两种方式和导入两种类型的Excel表格

    一.导出Excel表格的两种方式,其中两种方式指的是导出XML数据类型的Excel(即保存的时候可以只需要修改扩展名为.xls)和真正的Excel这两种. using System; using Sy ...

  2. PHP导出excel文件的几种方式

    PHP导出excel文件的几种方式 先说说动态生成的内容当作文件来下载的方法: 1.通过把Content-Type设置为application/octet-stream,可以把动态生成的内容当作文件来 ...

  3. 转:PHP导出excel文件的几种方式

    PHP导出excel文件的几种方式 文章来源:http://www.cnblogs.com/fredshare/archive/2012/10/29/2744243.html 先说说动态生成的内容当作 ...

  4. C&num;中的Excel操作【1】——设置Excel单元格的内容,打开Excel文件的一种方式

    前言 作为项目管理大队中的一员,在公司里面接触最多的就是Excel文件了,所以一开始就想从Excel入手,学习简单的二次开发,开始自己的编程之路! 程序界面 功能说明 打开文件按钮,可以由使用者指定要 ...

  5. Hive数据导入导出的几种方式

    一,Hive数据导入的几种方式 首先列出讲述下面几种导入方式的数据和hive表. 导入: 本地文件导入到Hive表: Hive表导入到Hive表; HDFS文件导入到Hive表; 创建表的过程中从其他 ...

  6. Hive创建表&vert;数据的导入&vert;数据导出的几种方式

    * Hive创建表的三种方式 1.使用create命令创建一个新表 例如:create table if not exists db_web_data.track_log(字段) partitione ...

  7. 数据库数据用Excel导出的3种方法

    将数据库数据用Excel导出主要有3种方法:用Excel.Application接口.用OleDB.用HTML的Tabel标签 方法1——Excel.Application接口: 首先,需要要Exce ...

  8. Hive数据导入导出的n种方式

    Tutorial-LoadingData Hive加载数据的6种方式 #格式 load data [local] inpath '/op/datas/xxx.txt' [overwrite] into ...

  9. &lbrack;Python&rsqb;xlrd 读取excel 日期类型2种方式

    有个excle表格须要做一些过滤然后写入数据库中,可是日期类型的cell取出来是个数字,于是查询了下解决的办法. 主要的代码结构 data = xlrd.open_workbook(EXCEL_PAT ...

随机推荐

  1. ElasticSearch在Azure中的集群配置和Auto-Scale

    最近在项目中ElasticSearch的使用越来越多,最新的项目中要求ES使用集群,在啥都不知道的情况下弄了两天后,终于搞定,因此写个笔记记录下. 1.首先我们需要创建一个Virtual networ ...

  2. JavaScript基础-面向对象编程&lt&semi;1&gt&semi;

    1.1 函数与对象  1.定义函数的方式定义类 定义类的方法: function class1(){ //类成员的定义及构造函数部分 } class1既是一个函数,也是一个类. 使用 new 操作符获 ...

  3. 常用的模式、JSON与DTO

    表现层的设计(一)——常用的模式.JSON与DTO 上几篇博文介绍了 业务逻辑层和数据访问层,我认为写博文的作用主要是向业界的读者交流一种思想,点到为止,至于学习架构设计,通过几篇博文是讲不清楚的,还 ...

  4. 69、django之Form组件

    本篇导航: 小试牛刀 Form类 常用选择插件 自定义验证规则 初始化数据 Django的Form主要具有一下几大功能: 生成HTML标签 验证用户数据(显示错误信息) HTML Form提交保留上次 ...

  5. AD预测论文研读系列1

    A Deep Learning Model to Predict a Diagnosis of Alzheimer Disease by Using 18F-FDG PET of the Brain ...

  6. 手动实现staticmethod和classmethod装饰器

    首先,staticmethod和classmethod装饰器是通过非数据描述符实现的.用法简单,这里就不细说了. 这里主要分析一下staticmethod和classmethod是如何通过描述符实现的 ...

  7. sql 经典面试题及答案&lpar;选课表&rpar;

    SQL数据库面试题以及答案 Student(Sno,Sname,Sage,Ssex) 学生表       Sno:学号:Sname:学生姓名:Sage:学生年龄:Ssex:学生性别Course(Cno ...

  8. ns3的输入输出奥秘(一) LOGGING系统

    1.LOGGING系统 (1)在我们之前对C++的理解,输出好像就是cout,然而 以myfirst.cc为例子 在我们前面的编写的代码中并没有出现cout,那他是如何输出. 可以回忆一下 LogCo ...

  9. springmvc验证数据

    1.引入jar包 com.springsource.javax.validation-1.0.0.GA.jar  规范(只是定义) hibernate-validator-4.1.0.Final.ja ...

  10. VC&plus;&plus; GetSafeHwnd用法

    GetSafeHwnd HWND GetSafeHwnd() const; 当我们想得到一个窗口对象(CWnd的派生对象)指针的句柄(HWND)时,最安全的方法是使用GetSafeHwnd()函数. ...