首页 > 其他分享 >.net操作excel

.net操作excel

时间:2023-10-20 09:01:16浏览次数:43  
标签:sheet string Missing Excel excel page 操作 net dt

.NET操作EXCEL

 

//页面初始化

//获取  _page并赋值

   public void Initial(SlnSuwfPage page)
        {
            this._page = page;
            this.BindButtonEvent("btnExport2");//给导出明细按钮添加事件
        }

 #region  绑定按钮事件       

  /// <summary>    

  /// 绑定按钮事件        

/// </summary>        

/// <param name="btnName"></param>        

private void BindButtonEvent(string btnName)        

{            

//导出明细按钮            

Control ctrl = this._page.FindControl(btnName);            

if (ctrl == null) return;

   if (btnName == "btnExport2")            

  {                

   Button btnExportEXCEL = (Button)ctrl;                

  if (btnExportEXCEL == null)

    return;                

  btnExportEXCEL.Click += new EventHandler(btnExportEXCEL_Click);            

  }        

}        

#endregion

   #region 注册按钮事件        

/// <summary>        

/// 注册按钮事件        

/// </summary>        

/// <param name="sender"></param>        

/// <param name="e"></param>        

void btnExportEXCEL_Click(object sender, EventArgs e)        

{            

     int count = _page.GridData.Rows.Count;

            string pk_value = _page.GetRowDataPrimaryKeys();            

    if (string.IsNullOrEmpty(pk_value))            

    {                

                _page.ShowMessage("请选择要导出的数据!");               

                 return;            

            }

            string[] str = pk_value.Split(',');            

            //调换字符数组的顺序,使导出的数据和页面显示的数据一样            

            //int Begin = 0;            

           //int End = str.Length - 1;           

          //while (End >= Begin)            

        //{            

       //    string t = str[Begin];            

//    str[Begin] = str[End];           

  //    str[End] = t;            

//    Begin++;          

   //    End--;           

  //}

            //选择一条数据时-----应急领料单           

  #region           

  if (str.Length == 1)         

    {             

    strFileName = "应急领料单.xls";     

  string strSql = @"select t.*,decode (ZT,2,'未出帐',3,'未补单',4,'已补单',5,'缺组件',6,'未下达',7,'已出账',1) ZT2 "          

       + "from (select YJLL_BM,SYDW,SGDW,ZZMC,LLYT,LLFZR,TEL,decode(GET_GETSFTD_FC(yjll_bm), 0, 3, 4) ZT,"           

      + "U_REGISTIME,BZ "           

      + "from WZGL_NEW_YJLL_TB "        

         + "where YJLL_BM='" + str[0] + "') t";

                string strSql2 = @"select WZ_ZSHBZM as WZ_BM,WZ_MC,JLDW,SLSL,ERP_DH,BZ "        

         + "from WZGL_NEW_YJLLWZ_TB "              

   + "where wz_bm='" + str[0] + "'";

                Dictionary<string, string> dic = new Dictionary<string, string>();        

         dic.Add("dt", strSql);              

   dic.Add("dt1", strSql2);

                DataSet ds = new DataSet();           

      foreach (KeyValuePair<string, string> k in dic)          

       {                 

    SlnDataAccess.FillDataSet(ds, k.Key, k.Value);           

      }          

       string strMsg = Salien.Utility.SUWF.ClsPrintExcel.ExportExcel("", ds, strFileName, false, "HTML");      

           if (strMsg == "")           

      {                 

    _page.ShowMessage("导出成功!");         

        }       

          else

                {            

         _page.ShowMessage("导出失败!" + strMsg);    

             }      

       }         

    #endregion

            //选择多条数据时-----应急领料单2           

  #region           

  else      

       {          

       //for (int i = 0; i < str.Length; i++)           

      //{               

  strFileName = "应急领料单2";             

    //string templateFilePath = AppDomain.CurrentDomain.BaseDirectory + "REPORT\\Templates\\" + FileName;        

         string fileFullName = AppDomain.CurrentDomain.BaseDirectory

+ "REPORT\\Generates\\" + strFileName + System.Guid.NewGuid().ToString() + ".xls";            

     string templateFilePath = strFilePath + strFileName + ".xls";

                //string YJLL_BM = str[i].ToString();

                string strSql = "select    ''''||YJLL_BM as YJLL_BM ,"     

+ " SYDW,"     

+ "  ''''||WZ_ZSHBZM as WZ_BM,"     

+ " ''''||WZ_MC as WZ_MC,"      

+ "JLDW,"    

  + " SLSL,"    

  + "'' as slsl,"     

+ " ERP_DH,  "  

    + " t.BZ as BZ1,"      

+ " SGDW,"     

  + "ZZMC,"      

+ "LLYT,"     

+ " LLFZR,  "     

+ "  ''''||TEL as TEL ,"

+ "decode(ZT,2, '未出帐',  3, '未补单', 4, '已补单', 5, '缺组件', 6,"    

   + "   '未下达',  7, '已出账',  1) ZT2,"   

  + "  U_REGISTIME  ,"   

   + " w.BZ"

+ " from"      

   + "   (select YJLL_BM,SYDW,SGDW,ZZMC,LLYT,LLFZR,  TEL,"     

    + "  decode(GET_GETSFTD_FC(yjll_bm), 0, 3, 4) ZT,"  

       + " U_REGISTIME, BZ  from WZGL_NEW_YJLL_TB "       

  + "  where YJLL_BM in(" + pk_value + ")) t,WZGL_NEW_YJLLWZ_TB w "     

    + "  where wz_bm(+)=YJLL_BM  order by YJLL_BM desc";

                DataTable dt = SlnDataAccess.GetDataTable(strSql);

                string str_Msg = OperatExcel(dt, templateFilePath, fileFullName, 4);

                //下载时要显示的文件名           

      string dstrSql = "select to_char(sysdate,'yyyy-mm-dd')  from dual";      

           string downloadName = SlnDataAccess.GetValueBySql(dstrSql).ToString() + ".xls";

                if (str_Msg == "")           

      {                   

  //下载文件方式               

      FileStream fileStream = new FileStream(fileFullName, FileMode.Open, FileAccess.Read, FileShare.Read);   

                  int length = (int)fileStream.Length;              

       byte[] filebyte = new byte[length];           

          fileStream.Read(filebyte, 0, length);          

           fileStream.Close();              

       _page.Response.Clear();        

             _page.Response.Charset = "GB2312";       

              _page.Response.ContentEncoding = System.Text.Encoding.UTF8;      

               // 添加头信息,为"文件下载/另存为"对话框指定默认文件名      

               _page.Response.AddHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(downloadName));                     // 添加头信息,指定文件大小,让浏览器能够显示下载进度      

               _page.Response.AddHeader("Content-Length", length.ToString());            

         // 指定返回的是一个不能被客户端读取的流,必须被下载                 

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

             // 把文件流发送到客户端                

     _page.Response.BinaryWrite(filebyte);       

              _page.Response.Flush();                 

    // 停止页面的执行              

       _page.Response.End();

                }               

  else               

  {             

        _page.ShowMessage("导出失败!" + str_Msg);          

       }            

     //}      

       }      

       #endregion

        }      

   #endregion

        #region 操作Excel   

      /// <summary>    

     ///        

/// </summary>   

      /// <param name="dt"></param>  

       /// <param name="strFileName"></param>

        public string OperatExcel(DataTable _dt, string templateFilePath, string fileFullName, int startRowIndex)   

      {        

     string strMsg = "";     

        //startRowIndex = startRowIndex + 1;      

       try        

     {           

      Microsoft.Office.Interop.Excel.Application app = null;  // Excel 对象          

       Microsoft.Office.Interop.Excel.Workbook workbook = null; // Workbook 对象       

          Microsoft.Office.Interop.Excel.Worksheet sheet = null; // Worksheet 对象         

        Microsoft.Office.Interop.Excel.Range range = null;         // Range 对象

                app = new Microsoft.Office.Interop.Excel.Application();               

  app.Visible = false;             

    app.DisplayAlerts = false;

                // 获取Workbook

                workbook = (Microsoft.Office.Interop.Excel.Workbook)(app.Workbooks.Add(templateFilePath));     

            sheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.ActiveSheet;            

     object[,] rangeValue;

                //  string strValue = "";

                int rowIndex = startRowIndex;            

     ////设置时间           

      //sheet.Cells[5, 1] = strExcelTime;

                int colIndex = 0;

                #region  填充内容

                range = sheet.get_Range(sheet.Cells[startRowIndex, 1], sheet.Cells[startRowIndex + _dt.Rows.Count - 1, _dt.Columns.Count]);                 rangeValue = new object[_dt.Rows.Count, _dt.Columns.Count];

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

    {                   

  for (int j = 1; j < _dt.Columns.Count; j++)      

               {         

                colIndex = j - 1;            

             rangeValue[i, colIndex] = _dt.Rows[i][j - 1];     

                }            

     }            

     range.set_Value(Type.Missing, rangeValue);         

        range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;        

         range.Borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;      

           range.Borders.Weight = Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin;            

     range.WrapText = true;//自动换行

                range.EntireRow.AutoFit();//行高自动调整         

                        #endregion

                #region  合并列        

         List<string> columnNameLst = new List<string>();//按列相同内容合并   

                columnNameLst.Add("YJLL_BM");//列名

                List<string> columnNameLst1 = new List<string>();//根据YJLL_BM确定合并        

         columnNameLst1.Add("SYDW");          

       columnNameLst1.Add("SGDW");//罐量          

       columnNameLst1.Add("ZZMC");         

        columnNameLst1.Add("LLYT");        

         columnNameLst1.Add("LLFZR");        

         columnNameLst1.Add("TEL");            

     columnNameLst1.Add("ZT2");         

        columnNameLst1.Add("U_REGISTIME");     

            columnNameLst1.Add("BZ");

                string ccName = "";             

    for (int c = 0; c < _dt.Columns.Count; c++)        

         {                 

    colIndex = c + 1;       

              ccName = _dt.Columns[c].ColumnName;   

                  if (!columnNameLst.Contains(ccName) && !columnNameLst1.Contains(ccName))          

           {                    

     continue;      

               }

                    for (int r = startRowIndex; r < _dt.Rows.Count + startRowIndex - 1; r++)       

              {                         if (columnNameLst.Contains(ccName))      

                   {                       

      string text1 = _dt.Rows[r - startRowIndex][c].ToString();       

                      string text2 = _dt.Rows[r - startRowIndex + 1][c].ToString();       

                      if (text1 == text2)          

                   {                     

            //sheet.get_Range(sheet.Cells[r, colIndex], sheet.Cells[r + 1, colIndex]).Merge(0);                                 Microsoft.Office.Interop.Excel.Range cc;                            

     cc = sheet.get_Range(sheet.Cells[r, colIndex], sheet.Cells[r + 1, colIndex]);               

                  cc.MergeCells = true;                  

           }

                        }                 

        else if (columnNameLst1.Contains(ccName))           

              {                       

      string text1 = _dt.Rows[r - startRowIndex][c].ToString();             

                string text2 = _dt.Rows[r - startRowIndex + 1][c].ToString();                

             string text3 = _dt.Rows[r - startRowIndex][0].ToString();           

                  string text4 = _dt.Rows[r - startRowIndex + 1][0].ToString();             

                if (text1 == text2 && text3 == text4)                 

            {                   

              sheet.get_Range(sheet.Cells[r, colIndex], sheet.Cells[r + 1, colIndex]).Merge(0);      

                       }                 

        }                   

  }     

            }       

          #endregion

                #region 保存

                //workbook.SaveAs(strFilePath + strFileName + ".xls",           

      // Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,    

             // Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing,       

          // Type.Missing, Type.Missing);           

      workbook.SaveAs(fileFullName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, false, false, null, null);

                #endregion

                sheet = null;        

         workbook.Close(false, System.Reflection.Missing.Value, System.Reflection.Missing.Value);         

        workbook = null;       

          app.Quit();          

       app = null;       

          GC.Collect();

                return strMsg;     

        }            

catch (Exception e)   

          {                

throw e;      

       }    

     }      

   #endregion

标签:sheet,string,Missing,Excel,excel,page,操作,net,dt
From: https://www.cnblogs.com/nuaaydh/p/17776221.html

相关文章

  • .net 多sheet页导出表格文件表格文件
     usingSystem;usingSystem.Data;usingSystem.Linq;usingSystem.Configuration;usingSystem.Web;usingSystem.Web.Security;usingSystem.Web.UI;usingSystem.Web.UI.WebControls;usingNPOI.HSSF.UserModel;usingNPOI.SS.UserModel;usingSystem.IO;//usingSystem.W......
  • 操作系统之段页式存储组织
    1、例题展示2、例题解决......
  • Linux操作系统从BIOS到bootloader是如何运行的
    操作系统一般都会在安装在硬盘上,在BIOS的界面上。你会看到一个启动盘的选项。启动盘有什么特点呢?它一般在第一个扇区,占512字节,而且以0xAA55结束。这是一个约定,当满足这个条件的时候,就说明这是一个启动盘,在512字节以内会启动相关的代码。这些代码是谁放在这里的呢?在Linux......
  • ASP.NET CORE学习笔记(host主机)
    1、扩展包 Microsoft.Extensions.Hosting2、包括Host、WebApplication3、示例1)honst 注意:<ProjectSdk="Microsoft.NET.Sdk">varbuilder=Host.CreateDefaultBuilder(args);varapp=builder.Build();app.Run();2)web......
  • 一个更复杂的 PHP 代码示例,我将展示一个购物车系统的基本实现,它包括商品类、购物车类
    一个更复杂的PHP代码示例,我将展示一个购物车系统的基本实现,它包括商品类、购物车类和一些基本的操作方法。<?php//定义商品类classProduct{private$name;private$price;publicfunction__construct($name,$price){$this->name=$name;$this->pri......
  • ASP.NET Core中对开放泛型(Open Generic)的依赖注入
    publicinterfaceIRepository<T>{voidAdd(Tentity);List<T>Get();}publicclassRepository<T>:IRepository<T>{List<T>_list=newList<T>();publicvoidAdd(Tentity){_list.Add(entit......
  • [Microsoft Azure] 如何查看 Azure Function的.NET SDK版本列表
    本文将介绍如何在MicrosoftAzure中查看和选择AzureFunction的.NETSDK版本列表,以便为您的项目选择合适的版本。在MicrosoftAzure中,AzureFunctions是一种用于在云端运行小型应用程序或功能的服务。它可以帮助我们在不需要管理基础设施的情况下快速构建和部署应用程......
  • [Microsoft Azure] 如何查看 Azure Function的.NET Runtime
    在本文中,我们将详细介绍如何在MicrosoftAzure中查看AzureFunction的.NETRuntime版本。了解如何找到所使用的.NET版本,确保您的Functions应用程序兼容并具有稳定性。在使用MicrosoftAzure的过程中,您可能会使用到AzureFunctions作为一个无服务器计算服务。而在......
  • Netty实践 -- echo
    Netty实践学习netty,可以从netty源码的netty-example模块开始。netty-example有一个例子echo,非常适合入门学习。这里稍微改造一下,用作示例学习。引入依赖包:<dependency><groupId>io.netty</groupId><artifactId>netty-all</artifactId>......
  • netty常用类
    netty架构图ServerBootstrap、BootstrapServerBootstrap:服务器的引导类,可以绑定服务器和端口,配置Channel、ChannelHandler等。Bootstrap:客户端的引导类。可以开启客户端,连接服务端的端口,配置Channel、ChannelHandler等。EventLoopGroupEventLoopGroup用于处理基于Ch......