zoukankan      html  css  js  c++  java
  • c#导出到excel

      //导出Excel的方法
      private void ExportExcel()
      {
       DataSet ds=dtsSelect;//数据源
       if(ds==null) return;

       string saveFileName="";
       bool fileSaved=false;
       SaveFileDialog saveDialog=new SaveFileDialog();
       saveDialog.DefaultExt ="xls";
       saveDialog.Filter="Excel文件|*.xls";
       saveDialog.FileName ="Sheet1";
       saveDialog.ShowDialog();
       saveFileName=saveDialog.FileName;
       if(saveFileName.IndexOf(":")<0) return; //被点了取消

       Excel.Application xlApp=new Excel.Application();

       if(xlApp==null)
       {
        MessageBox.Show("无法创建Excel对象,可能您的机子未安装Excel");
        return;
       }

       Excel.Workbooks workbooks=xlApp.Workbooks;
       Excel.Workbook workbook=workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
       Excel.Worksheet worksheet=(Excel.Worksheet)workbook.Worksheets[1];//取得sheet1
       //写入字段
       for(int i=0;i<ds.Tables[0].Columns.Count;i++)
       {
        worksheet.Cells[1,i+1]=ds.Tables[0].Columns[i].ColumnName;
       }
       //写入数值
       
       for(int r=0;r<ds.Tables[0].Rows.Count;r++)
       {
        for(int i=0;i<ds.Tables[0].Columns.Count;i++)
        {
         worksheet.Cells[r+2,i+1]=ds.Tables[0].Rows[r][i];
        }
        System.Windows.Forms.Application.DoEvents();
       }
       worksheet.Columns.EntireColumn.AutoFit();//列宽自适应。
       if(cmbxType.Text!="Notification")
       {
        Excel.Range rg=worksheet.get_Range(worksheet.Cells[2,2],worksheet.Cells[ds.Tables[0].Rows.Count+1,2]);
        rg.NumberFormat="00000000";
       }
       if(saveFileName!="")
       {
        try
        {
         workbook.Saved =true;
         workbook.SaveCopyAs(saveFileName);
         fileSaved=true;
        }
        catch(Exception ex)
        {
         fileSaved=false;
         MessageBox.Show("导出文件时出错,文件可能正被打开!\n"+ex.Message);
        }
       }
       else
       {
        fileSaved=false;
       }
       xlApp.Quit();
       GC.Collect();//强行销毁
       if(fileSaved && System.IO.File.Exists(saveFileName)) System.Diagnostics.Process.Start(saveFileName); //打开EXCEL
      }

    ---------------------------------------------------------------

    aspnetxBI笔记系列索引:

    使用SQL Server Analysis Services数据挖掘的关联规则实现商品推荐功能

    一起玩转SQL Server 2012 下的分析服务

    使用SQL Server分析服务定位目标用户

    ---------------------------------------------------------------

    来自博客园aspnetx宋卫东

  • 相关阅读:
    centos7安装YouCompleteMe,vim打造成C++的IDE
    java循环定时器@Scheduled的使用
    js使用“toFixed( )”保留小数点后两位
    linux小本
    解决Maven资源过滤问题
    在Maven普通项目上添加Web app的支持
    项目中添加lib依赖
    回顾Servlet
    Tomcat 中文乱码
    Initialization failed for 'https://start.spring.io' Please check URL
  • 原文地址:https://www.cnblogs.com/aspnetx/p/397942.html
Copyright © 2011-2022 走看看