ASP.Net中使用Excel做报表

ASP.Net中使用Excel做报表

 

1.首先需要用Excel做一个模板,模板格式根据需求自行定义格式.

 

2.复制模板并填充数据,然后下载

           /// <summary>

           ///根据Excel模板文件,复制一个新的Excel文件并填充数据。

           /// </summary>

           ///<param name="dt">将要用于填充的数据</param>

           ///<param name="sNewFileName">Excel文件的名称</param>

        public void CopyExcelToNew(DataTable dt, out string sNewFileName)

        {

            string sOldFileName = "MSC";

            sNewFileName = sOldFileName + String.Format("{0:yyyyMMddHHmmss}", DateTime.Now) + ".xls";

 

            string sSysDir = Server.MapPath("~/");//表示当前应用级程序的目录

            string sSysCurrDir = Server.MapPath("./");//表示所在页面的当前目录

 

                 //Excel模板所在的路径

            string sOldFilePath = sSysDir + string.Format(@"/WOImportTemplate/{0}.xls", sOldFileName);

           

            //Excel文件所在的路径

            string sNewFilePath = sSysDir + @"/DataExchange/Excel/" + sNewFileName;

 

 

            #region copy file

            File.Copy(sOldFilePath, sNewFilePath, true);

            FileInfo fi = new FileInfo(sNewFilePath);

            fi.Attributes = FileAttributes.Normal;

 

            #endregion

 

            #region fill data into excel

            string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=True;Data Source=" + sNewFilePath + ";Extended Properties=Excel 8.0;";

            using (System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(strConn))

            {

                conn.Open();

                OleDbCommand objCmd = new OleDbCommand();

                objCmd.Connection = conn;

                string sql = string.Empty;

                int i = 1;

                foreach (DataRow row in dt.Rows)

                {

                    if (i == 1)

                    {

                        sql = string.Format("UPDATE [Sheet1$] SET [序号]={0},[库位编码]='{1}',[物料编码]='{2}',[物料名称]='{3}',[规格/型号]='{4}',[制造商/品牌]='{5}',[单位]='{6}',[库存数量]={7},[盘点数量]={7} WHERE [序号]=0;", 1, row["WarehouseNumberWCode"], row["MaterialCode"], row["MaterialName"].ToString().Replace("'", "''"), row["ModelNumberName"].ToString().Replace("'", "''"), row["ManufacturerName"].ToString().Replace("'", "''"), row["Unit"], row["Qty"]);

                        i++;

                    }

                    else

                    {

                        sql = "INSERT INTO [Sheet1$]([序号],[库位编码],[物料编码],[物料名称],[规格/型号],[制造商/品牌],[单位],[库存数量],[盘点数量])";

                        sql += string.Format("VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{7}');", i++, row["WarehouseNumberWCode"], row["MaterialCode"], row["MaterialName"].ToString().Replace("'", "''"), row["ModelNumberName"].ToString().Replace("'", "''"), row["ManufacturerName"].ToString().Replace("'", "''"), row["Unit"], row["Qty"]);

                    }

                    objCmd.CommandText = sql;

                    objCmd.ExecuteNonQuery();

                }

                if (i == 1)

                {

                    sql = "UPDATE [Sheet1$] SET [序号]=null,[库位编码]=null,[物料编码]=null,[物料名称]=null,[规格/型号]=null,[制造商/品牌]=null,[单位]=null,[库存数量]=null WHERE [序号]=0;";

                    objCmd.CommandText = sql;

                    objCmd.ExecuteNonQuery();

                }

 

                conn.Close();

            }

            #endregion

 

            #region

 

            #endregion

 

        }

        /// <summary>

        ///下载文件,这个方法可以通用,不需修改.

        /// </summary>

        ///<param name="excelFile">文件在服务器上的地址</param>

        ///<param name="excelName">文件名称</param>

        ///<param name="delFile">下载完成后是否删除服务器中的文件。</param>

        public static void DownloadExcel(string excelFile, string excelName, bool delFile)

        {

            FileInfo fi = new FileInfo(excelFile);//excelFile为文件在服务器上的地址

            HttpResponse contextResponse = HttpContext.Current.Response;

            contextResponse.Clear();

            contextResponse.Buffer = true;

            contextResponse.Charset = "GB2312"; //设置了类型为中文防止乱码的出现

            contextResponse.AppendHeader("Content-Disposition", String.Format("attachment;filename={0}", excelName)); //定义输出文件和文件名

            contextResponse.AppendHeader("Content-Length", fi.Length.ToString());

            contextResponse.ContentEncoding = Encoding.Default;

            contextResponse.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。

 

            contextResponse.WriteFile(fi.FullName);

            contextResponse.Flush();

            if (delFile)

            {

                fi.Delete();

            }

            contextResponse.End();

        }

       

 3.调用方法

         DataTable dt = SqlHelper.ExecuteDataTable(global.ConnString, CommandType.Text, sql.ToString());

            if (dt.Rows.Count > 0)

            {

                string sNewFileName = string.Empty;

                CopyExcelToNew(dt, out sNewFileName);

 

                string jsNewFileName = Server.MapPath("~/") + @"/DataExchange/Excel/" + sNewFileName;

                new MSCExport().DownloadExcel(jsNewFileName, this.WONumber + ".xls");

            }

            else

            {

                this.Alert("没有检测到库存资料,请确认。");

            }

           

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这是以个c#报表例子,      //打开连接      conReport.Open();      //准备连接对象以把获取的数据放入数据集      cmdReport.CommandType = CommandType.Text;      cmdReport.Connection = conReport;      cmdReport.CommandText = "Select TOP 5 * FROM Products Order By ProductName";      //从命令对象读取数据      drReport = cmdReport.ExecuteReader();      //有了ADO.NET,可把读取来的数据直接加载到数据集      dsReport.Tables[0].Load(drReport);      //关闭读取及连接      drReport.Close();      conReport.Close();      //为查看器提供本地报表数据 this.reportViewer1.LocalReport.ReportEmbeddedResource =      "报表问题.rptProductList.rdlc";      //准备报表数据源      ReportDataSource rds = new ReportDataSource();      rds.Name = "dsProduct_dtProductList";      rds.Value = dsReport.Tables[0]; this.reportViewer1.LocalReport.DataSources.Add(rds);      //加载报表查看器 this.reportViewer1.RefreshReport();    }    catch (Exception ex)    {      //显示错误信息      MessageBox.Show(ex.Message);    }    finally    {      //检查连接是否仍然打开,如果是,关闭它。      if (conReport.State == ConnectionState.Open)      {        conReport.Close();      }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值