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("没有检测到库存资料,请确认。");

            }

           

这是以个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();      }
Excel Report Builder<br>Excel Report 万能报表平台<br>Excel 使用WEB服务(webservice)访问远程数据库<br>使用本软件可以使你的应用系统(数据库)和excel相连。<br>可以把它嵌入到你的应用系统里,为应用系统的外挂程序。<br>可以利用excel强大的编辑功能,随心所欲地开发出精美的报表。<br>本软件基于Web Service(Web服务)新技术,所以它支持web网络,<br>可以通过Internet访问远程数据。<br>只要你稍懂SQL,就可以在Excel Report 万能报表平台上设计报表。<br>通过设置字段,参数等信息来设计报表。<br>BI智能报表,支持透视表。<br>提供存储过程接口,便于用户二次开发。<br>有用户管理,报表权限的管理。<br>支持多语种。 <br>软件环境:<br> 客户端: Windows 2000及以上版本,Microsoft Office 2000及以上版本<br> 服务器端:Windows和Linux都可以,jsdk1.4,tomcat5<br> 数据库:支持Oracle, SQL Server 等数据库。<br>下载地址:<br>报表安装包:<br>http://203.208.248.203:81/pan/Excel/j2sdk-1_4_2_06-windows-i586-p.exe<br>http://203.208.248.203:81/pan/Excel/jakarta-tomcat-5.0.27.exe<br>http://203.208.248.203:81/pan/Excel/setup4.42.rar<br>联系方式:<br> http://pansoft.ik8.com<br> QQ: 10124900<br>MSN: bear_pan@hotmail.com<br>E_Mail: bear_pan@163.com<br><br>Excel Report Builder<br>Excel Report Builder is an easy and convenient tool for the creation and customization of reports which takes advantage of the formatting and presentation capabilities of Microsoft Excel. The program allows the rapid construction of reports.A GUI style design environment, which allows the user to design their reports visually inside MS Excel. Reports can be saved and then viewed and printed as pure Excel documents. <br>The reports are created and printed rapidly.In fact, it is by harnassing the power of Excel that gives Excel Report Builder these abilities.No technical knowledge is needed in order for the user to customise his or her own reports. <br><br>Key Features of the Database Report Builder for Excel include:<br> Report creation using Microsoft Excel<br> Get data through webservice,so you can get remote data <br> Support of the SQL-queries for the data sets creation<br> Calling of the stored procedures for the data sets creation<br> Creation of the reports with parameters<br> Work with the Microsoft Excel macros<br> Charts creation in a report<br><br>Software:<br> Client: Windows 2000 or above,Microsoft Office 2000 or above<br> Server: jsdk1.4,tomcat5<br> Database: Oracle or SQL Server <br>Download:<br>Excel Report Builder:<br>http://203.208.248.203:81/pan/Excel/j2sdk-1_4_2_06-windows-i586-p.exe<br>http://203.208.248.203:81/pan/Excel/jakarta-tomcat-5.0.27.exe<br>http://203.208.248.203:81/pan/Excel/setup4.42.rar<br><br>Contact:<br> http://pansoft.ik8.com <br> QQ: 10124900<br>MSN: bear_pan@hotmail.com<br>E_Mail: bear_pan@163.com<br><br>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值