首页 > 编程语言 >ASP.NET 调用Excel模版,导出Excel文件

ASP.NET 调用Excel模版,导出Excel文件

时间:2022-11-16 13:01:47浏览次数:53  
标签:Rows filePath Excel ASP 配件 NET dt 入库 出库

--引用命名空间
using System.Configuration;
using System.Data.OleDb;
using System.Data.SqlClient;
/// <summary>
/// 导出正式Excel文件,用于导入盘点数据

/// </summary>

/// <param name="ds2"></param>

private void ToExcel(DataSet ds)

{

if (ds.Tables[0].Rows.Count > 0)

{

DataTable dt = ds.Tables[0];

string filename = "KCPD_" + Session["UserName"].ToString() + "_" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls";

//临时存放路径

string filePath = Server.MapPath("~/upload/" + filename);

//Excel模版

string masterPath = Server.MapPath("~/upload/Master/PDCK.xls");

//复制Excel模版

File.Copy(masterPath, filePath);



#region 将文件的只读勾取消 以免发生不必要的错误

// 先把文件的属性读取出来

FileAttributes attrs = File.GetAttributes(filePath);



// 下面表达式中的 1 是 FileAttributes.ReadOnly 的值

// 此表达式是把 ReadOnly 所在的位改成 0,

attrs = (FileAttributes)((int)attrs & ~(1));



File.SetAttributes(filePath, attrs);

#endregion



// 使用OleDb驱动程序连接到副本

OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;'");

using (conn)

{

conn.Open();

// 增加记录

for (int i = 0; i < dt.Rows.Count; i++)

{

OleDbCommand cmd = new OleDbCommand(@"INSERT INTO [Sheet1$]

(

[配件ID],[识别码],[配件名称],[配件规格],[配件代码],[版本],

[上月库存],[采购入库],[良品入库],[维修返回],[维修入库],

[调整库存],[调拨入库],[销售出库],[免费出库],

[调拨出库],[维修出库],[其它出库],[现有库存],[盘点库存]

)

values('" + dt.Rows[i]["配件ID"] + "', '" + dt.Rows[i]["识别码"] + "','" + dt.Rows[i]["配件名称"] + "', '" + dt.Rows[i]["配件规格"] + "','" + dt.Rows[i]["配件代码"] + "', '" + dt.Rows[i]["版本"] + "', '" + dt.Rows[i]["上月库存"] + "','" + dt.Rows[i]["采购入库"] + "', '" + dt.Rows[i]["良品入库"] + "', '" + dt.Rows[i]["维修返回"] + "','" + dt.Rows[i]["维修入库"] + "', '" + dt.Rows[i]["调整库存"] + "', '" + dt.Rows[i]["调拨入库"] + "', '" + dt.Rows[i]["销售出库"] + "', '" + dt.Rows[i]["免费出库"] + "', '" + dt.Rows[i]["调拨出库"] + "', '" + dt.Rows[i]["维修出库"] + "', '" + dt.Rows[i]["其它出库"] + "', '" + dt.Rows[i]["现有库存"] + "', '" + dt.Rows[i]["盘点库存"] + "')", conn);

cmd.ExecuteNonQuery();

}

conn.Close();



}

// 输出副本的二进制字节流

HttpContext.Current.Response.Charset = "UTF-8"; // 或UTF-7 以防乱码

HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;

Response.ContentType = "application/ms-excel";

Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(System.Text.Encoding.GetEncoding(65001).GetBytes(filename)));

Response.BinaryWrite(File.ReadAllBytes(filePath));

//删除副本

File.Delete(filePath);

}

}

标签:Rows,filePath,Excel,ASP,配件,NET,dt,入库,出库
From: https://blog.51cto.com/likely/5855893

相关文章