将数据集导出到Excel

方法一: 将数据集在Excel中打开

 

添加引用:

引用   右键→添加引用 → 扩展   Microsoft.Office.Interop.Excel

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DAL;

namespace RRBManage
{
public partial class OutExcel : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
//点击导出到Excel按钮事件
protected void btnOut_Click(object sender, EventArgs e)
{

//得到要导出的数据集
DataSet ds = AdminUserService.GetList("");
if (DataSetToExcel(ds, true))
{
ClientScript.RegisterStartupScript(this.GetType(), "msg", "<script>alert(导出成功!');</script>");
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "msg", "<script>alert(导出失败!');</script>");
}

}

//导出的方法
public bool DataSetToExcel(DataSet dataSet, bool isShowExcle)
{
DataTable dataTable = dataSet.Tables[0];
int rowNumber = dataTable.Rows.Count;
int columnNumber = dataTable.Columns.Count;

if (rowNumber == 0)
{
// MessageBox.Show("没有任何数据可以导入到Excel文件!");
return false;
}
try
{
//建立Excel对象
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
excel.Application.Workbooks.Add(true);
excel.Visible = isShowExcle;//是否打开该Excel文件

//填充数据
for (int c = 0; c < rowNumber; c++)
{
for (int j = 0; j < columnNumber; j++)
{
excel.Cells[c + 1, j + 1] = dataTable.Rows[c].ItemArray[j];
}
}
return true;
}
catch (Exception)
{
return false;
}
}

}
}

 

 

 

方法二 :用流,把数据以table的形式保存。

 

/// <param name="e"></param>
//点击导出到Excel按钮事件
protected void btnOut_Click(object sender, EventArgs e)
{
DataSet ds = AdminUserService.GetList("");
var ext = ".xls";
string downFileName = "";
downFileName += string.Format("_{0}{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), ext);
CreateExcel(ds, downFileName);
}
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 = "";
//定义表对象与行对象,同时用DataSet对其值进行初始化
DataTable dt = ds.Tables[0];
DataRow[] myRow = dt.Select();//可以类似dt.Select("id>10")之形式达到数据筛选目的
int i = 0;
int cl = dt.Columns.Count;
//取得数据表各列标题,各标题之间以/t分割,最后一个列标题后加回车符
for (i = 0; i < cl; i++)
{

colHeaders += dt.Columns[i].Caption.ToString() + "\t";
}
colHeaders += "\r";
resp.Write(colHeaders);
//向HTTP输出流中写入取得的数据信息
//逐行处理数据
foreach (DataRow row in myRow)
{
//当前行数据写入HTTP输出流,并且置空ls_item以便下行数据
for (i = 0; i < cl; 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();
}

posted @ 2015-09-02 11:11  馒头什么的最喜欢了  阅读(244)  评论(1编辑  收藏  举报