asp.net导出excel

T_long 2012-06-20 10:13:10
画了一个table导出的excel的,但是导 出来的不是标准的格式
怎么导出一个标准的excel
这个是导出的代码
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.Buffer = true;
System.Web.HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
System.Web.HttpContext.Current.Response.Charset = "GB2312";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + MainID + SubID + Date + ".xls");
System.Web.HttpContext.Current.Response.Write(content.ToString());
System.Web.HttpContext.Current.Response.End();
...全文
261 19 打赏 收藏 转发到动态 举报
写回复
用AI写文章
19 条回复
切换为时间正序
请发表友善的回复…
发表回复
luoguiming2012 2012-09-20
  • 打赏
  • 举报
回复
找一下NPOI 简单易用,不需要安装EXCEL
Ryan20082009 2012-09-20
  • 打赏
  • 举报
回复
{
HQSoft.Common.MessageBox.Show(this, "对不起,您导入的Excel数据格式模板不正确,与第1列的列名“客户编号”不匹配,请修改正确后再重新导入!!");
return;
}
if (wst.Cells[0, 1].Value == null || wst.Cells[0, 1].Value.ToString().Trim() != "商品编号")
{
HQSoft.Common.MessageBox.Show(this, "对不起,您导入的Excel数据格式模板不正确,与第2列的列名“商品编号”不匹配,请修改正确后再重新导入!!");
return;
}

else
{
int Good = 0;
int Bad = 0;
string ss = "";
string sss = "";
for (int i = 0; i < dr.Length; i++)
{
string CustomerNo, ItemNo;
CustomerNo = dr[i]["客户编号"].ToString().Trim();
ItemNo = dr[i]["商品编号"].ToString().Trim();

if ((CustomerNo == "") || (CustomerNo == null))
{
sss += "第" + (i + 2) + "行客户编号不能为空,";
}
if ((ItemNo == "") || (ItemNo == null))
{
sss += "第" + (i + 2) + "行商品编号不能为空,";
}
else
{
try
{
//导入到SQL Server中
tmpModel.CustomerNo = CustomerNo;
tmpModel.ItemNo = ItemNo;
tmpModel.CreateDate = DateTime.Now.ToLocalTime();
tmpModel.CreateUserID = UserModel.UserID;
//if (tmpBll.GetRecordCount(" CustomerNo='" + CustomerNo + "'") > 0)
//{
// Bad += 1;
// ss += i + 1 + ",";
// sss += "第" + (i + 2) + "客户编号重复,";
//}
//else
//{
Good += 1;
tmpBll.Add(tmpModel);
//}
}
catch (Exception)
{
Response.Write("<script language='javascript'>alert('数据导入失败!');window.location='customer_select.aspx'</script>");
}
}
}
if (ss.Length > 0 || sss.Length > 0)
{
tmpBll.Delete();
HQSoft.Common.MessageBox.Show(this, "数据导入成功" + Good + ",失败" + Bad + ",错误行数" + ss + "错误详细" + sss);
ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script>shows();</script>");
}
else
{
this.GridView_tmpCustomerItem.DataSource = tmpBll.GetList("");
GridView_tmpCustomerItem.DataBind();
ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script>shows();</script>");
}
}
}
}
}
}
//正是表确定导入。
protected void Btn_Add_Click(object sender, EventArgs e)
{
HQSoft.HQBLL.TB_CustomerItem tbBll = new HQBLL.TB_CustomerItem();
HQSoft.HQModel.TB_CustomerItem tbModel = new HQModel.TB_CustomerItem();
for (int i = 0; i < this.GridView_tmpCustomerItem.Rows.Count; i++)
{
if (this.GridView_tmpCustomerItem.Rows[i].Cells[0].Text == " ")
{
this.GridView_tmpCustomerItem.Rows[i].Cells[0].Text = "";
}
else
{
tbModel.CustomerNo = this.GridView_tmpCustomerItem.Rows[i].Cells[0].Text.Trim().ToString();
}
if (this.GridView_tmpCustomerItem.Rows[i].Cells[1].Text == " ")
{
this.GridView_tmpCustomerItem.Rows[i].Cells[1].Text = "";
}
else
{
tbModel.ItemNo = this.GridView_tmpCustomerItem.Rows[i].Cells[1].Text.Trim().ToString();
}
tbModel.CreateUserID = UserModel.UserID;
tbModel.CreateDate = DateTime.Now.ToLocalTime();
tbBll.Add(tbModel);
}
tmpBll.Delete();
HQSoft.Common.MessageBox.Show(this, "数据导入成功!");
this.CustomerItem_Bind();
}
Ryan20082009 2012-09-20
  • 打赏
  • 举报
回复
2、 //导出时候下载并上传临时文件。
private bool DownLoadFile(string _FilePath, string _FileName)
{
try
{
System.IO.FileStream fs = System.IO.File.OpenRead(_FilePath + "\\" + _FileName);
byte[] FileData = new byte[fs.Length];
fs.Read(FileData, 0, (int)fs.Length);
Response.Clear();
Response.AddHeader("Content-Type", "application/ms-excel");
string FileName = System.Web.HttpUtility.UrlEncode(System.Text.Encoding.UTF8.GetBytes(_FileName));
Response.AddHeader("Content-Disposition", "inline;filename=" + System.Convert.ToChar(34) + FileName + System.Convert.ToChar(34));
Response.AddHeader("Content-Length", fs.Length.ToString());
Response.BinaryWrite(FileData);
fs.Close();
//删除服务器临时文件
//System.IO.File.Delete(_FilePath + "\\" + _FileName);
Response.Flush();
Response.End();
return true;
}
catch (Exception ex)
{
ex.Message.ToString();
return false;
}
}
public override void VerifyRenderingInServerForm(Control control)
{
}
3、 //Excel导入DtataSet操作。
public DataSet ExecleToDataSet(string filenameurl, string table)
{
DataSet ds = new DataSet();
try
{
string strConn = "Provider=Microsoft.Jet.OleDb.4.0;" + "data source=" + filenameurl + ";Extended Properties='Excel 8.0; HDR=YES; IMEX=1'";
OleDbConnection conn = new OleDbConnection(strConn);
OleDbDataAdapter odda = new OleDbDataAdapter("select * from [Sheet1$]", conn);
odda.Fill(ds, table);
}
catch (Exception)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('Excel文件数据有误!');</script>");

}
return ds;
}
4、导入
//确定导入
protected void but_tmp_Import_Click(object sender, EventArgs e)
{

if (this.FileUpload1.FileName.ToString() == "")
{
Response.Write("<script language='javascript'>alert('导入文件不能为空,请先上传!');</script>");
}
if (this.FileUpload1.HasFile)
{
string fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();
if (fileExtension != ".xls")
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('导入仅支持.xls文件,请重新选择!');</script>");
return;
}
else
{
string path = Server.MapPath("~/Excel/");
string filetime = DateTime.Now.ToString("yyyyMMddHHmmss");//时间字段区分文件(同名文件覆盖)
string fiepath = path + "\\" + filetime + "\\" + FileUpload1.FileName;
//string fiepath = path + "\\" + fu_Excel.FileName;
if (!System.IO.Directory.Exists(path + "\\" + filetime))
{
System.IO.Directory.CreateDirectory(path + "\\" + filetime);
}
FileUpload1.PostedFile.SaveAs(fiepath);
//上传操作。
DataSet ds = ExecleToDataSet(fiepath, FileUpload1.FileName);
if (ds.Tables.Count == 0)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>Show('Excel表为空表,无数据!');</script>");
return;
}
DataRow[] dr = ds.Tables[0].Select();
int rowsnum = ds.Tables[0].Rows.Count;
if (rowsnum == 0)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>Show('Excel表为空表,无数据!');</script>");
return;
}
Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook();
workbook.Open(fiepath);
Aspose.Cells.Worksheets wsts = workbook.Worksheets;
if (wsts.Count > 0)
{
Aspose.Cells.Worksheet wst = wsts[0];
if (wst.Cells[0, 0].Value == null || wst.Cells[0, 0].Value.ToString().Trim() != "客户编号")
Ryan20082009 2012-09-20
  • 打赏
  • 举报
回复
我给你一个例子,我已经测试成功的:
1、执行导出按钮
//导出客户信息。
protected void but_ExcelImport_Click(object sender, EventArgs e)
{
HQSoft.HQBLL.TB_Customer tbBll = new HQBLL.TB_Customer();
Aspose.Cells.Workbook workBook = new Aspose.Cells.Workbook();
Aspose.Cells.Worksheet sheet = workBook.Worksheets[0];
DataTable dt = tbBll.GetList("").Tables[0];
for (int i = 0; i < dt.Rows.Count; i++)
{
sheet.Cells[0, 0].PutValue("客户编号");
sheet.Cells[0, 1].PutValue("客户名称");
sheet.Cells[0, 2].PutValue("客户全称");
sheet.Cells[0, 3].PutValue("快捷录入");
sheet.Cells[0, 4].PutValue("客户类型");
sheet.Cells[0, 5].PutValue("业务人员");
sheet.Cells[0, 6].PutValue("客户主联系人");
sheet.Cells[0, 7].PutValue("客户主联系电话");
sheet.Cells[0, 8].PutValue("客户邮件");
sheet.Cells[0, 9].PutValue("客户地址");
sheet.Cells[0, 10].PutValue("客户传真");
sheet.Cells[0, 11].PutValue("结算周期");
sheet.Cells[0, 12].PutValue("结算方式");
DataRow dr = dt.Rows[i];
sheet.Cells[i + 1, 0].PutValue(dt.Rows[i][1]);
sheet.Cells[i + 1, 1].PutValue(dt.Rows[i][2]);
sheet.Cells[i + 1, 2].PutValue(dt.Rows[i][3]);
sheet.Cells[i + 1, 3].PutValue(dt.Rows[i][4]);
sheet.Cells[i + 1, 4].PutValue(dt.Rows[i][5]);
sheet.Cells[i + 1, 5].PutValue(dt.Rows[i][6]);
sheet.Cells[i + 1, 6].PutValue(dt.Rows[i][7]);

sheet.Cells[i + 1, 7].PutValue(dt.Rows[i][8]);
sheet.Cells[i + 1, 8].PutValue(dt.Rows[i][9]);
sheet.Cells[i + 1, 9].PutValue(dt.Rows[i][10]);
sheet.Cells[i + 1, 10].PutValue(dt.Rows[i][11]);
sheet.Cells[i + 1, 11].PutValue(dt.Rows[i][12]);
sheet.Cells[i + 1, 12].PutValue(dt.Rows[i][13]);
}
string fileName = "";
fileName = "Customer_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls"; // 文件名
workBook.Save(Server.MapPath("../Customer/tmpCustomer/" + fileName));
DownLoadFile(Server.MapPath("../Customer/tmpCustomer/"), fileName);
}
peng_hai_bo 2012-09-20
  • 打赏
  • 举报
回复

推荐你个 OpenXml或者CloseXml 这两个插件,都不需要在服务器上安装Excel的 只适合Excel2007或以上的,因为微软在2007开始Excel的地层结构改成了用XML来组成
H_Gragon 2012-09-20
  • 打赏
  • 举报
回复
你的导出excel的方法,好像少了个中重要的方法,给你个实例:地址
likevs 2012-09-20
  • 打赏
  • 举报
回复
这种功能需求现在都普遍化了,网上已有很多完美的方案了,自己选
應燁軍 2012-09-20
  • 打赏
  • 举报
回复
Aspose.Cells +1 ...这个我用过不错,不需要office支持,重要的是有破解版
xielei4552 2012-09-19
  • 打赏
  • 举报
回复
#region 导出excel created by sharestone 2012-04-07
/// <summary>
/// 导出Excel
/// </summary>
/// <param name="Response">当前Response对象</param>
/// <param name="fileName">导出的文件名</param>
/// <param name="content">要导出的内容</param>
public static void ExportToExcel(HttpResponse Response, string fileName, string content)
{
Response.Clear();
Response.Buffer = true;
Response.Charset = "utf-8";
Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8));
//如果设置称gb2312,导出可能有乱码
Response.ContentEncoding = Encoding.UTF8;
//设置导出为excel
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
Response.Write(content);
Response.Flush();
Response.End();
}
#endregion

调用的时候
protected void Page_Load(object sender, EventArgs e)
{
var isExport = Request.Form["hidIsExport"] == null ? false : bool.Parse(Request.Form["hidIsExport"]);

if (isExport) //如果是导出命令,则导出
{
var str = Request.Form["hidContent"];
string decodeStr = Server.UrlDecode(str);//解码
CommonMethod.ExportToExcel(Response, "MarketingActivityReport.xls", decodeStr);
}
}
上面hidContent就是要导出的内容
T_long 2012-06-20
  • 打赏
  • 举报
回复
出了这两个方法导出,还有其他的方法吗?导出的时候里面有个下拉框的设置
T_long 2012-06-20
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 的回复:]
服务器上需要安装啊,xls文件格式没公开,只能Excel程序可以生成完全标准的格式。
[/Quote]
他们说装上excel不安全,不让安装
孟子E章 2012-06-20
  • 打赏
  • 举报
回复
asp.net程序 不建议使用这个,一般导出兼容的格式就可以了,
孟子E章 2012-06-20
  • 打赏
  • 举报
回复
服务器上需要安装啊,xls文件格式没公开,只能Excel程序可以生成完全标准的格式。
T_long 2012-06-20
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 的回复:]
你这是html的格式的,标准的格式要使用Microsoft.Office.Interop.Excel.
http://www.dotblogs.com.tw/finalevil/archive/2008/09/28/5517.aspx
[/Quote]
服务器上面没有装excel,可以用这个using Microsoft.Office.Interop.Excel吗?
我以前就是用的这个导出,导入的,可是发布以后就报错了
E次奥 2012-06-20
  • 打赏
  • 举报
回复
用文件流导出试试!
  • 打赏
  • 举报
回复
http://www.dotblogs.com.tw/finalevil/archive/2008/09/28/5517.aspx
孟子E章 2012-06-20
  • 打赏
  • 举报
回复
你这是html的格式的,标准的格式要使用Microsoft.Office.Interop.Excel.
http://www.dotblogs.com.tw/finalevil/archive/2008/09/28/5517.aspx
  • 打赏
  • 举报
回复
用 org.in2bits.MyXls 这个组件试试,网上有教程。我一直再用
yzf86211861 2012-06-20
  • 打赏
  • 举报
回复
去搜下这个东西
Aspose.Cells
这个在导出 Excel 的 时候相当不错.

62,074

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧