[C#] C#导入导出数据到Excel的通用类代码 →→→→→进入此内容的聊天室

来自 , 2020-11-21, 写在 C#, 查看 123 次.
URL http://www.code666.cn/view/c4414e53
  1. ///////////////////////////////////////////////////////////////////////////
  2. //Purpose:Excel文件导入导出,需引用Microsoft Excel 11.0 Object Library
  3. //Author: Dangmy
  4. //Date: 2007-03-09
  5. //Version: 1.0
  6. ///////////////////////////////////////////////////////////////////////////
  7.  
  8. public class ExcelIO
  9. {
  10.      private int _ReturnStatus;
  11.      private string _ReturnMessage;
  12.  
  13.      /// <summary>
  14.      /// 执行返回状态
  15.      /// </summary>
  16.      public int ReturnStatus
  17.      {
  18.          get{return _ReturnStatus;}
  19.      }
  20.  
  21.      /// <summary>
  22.      /// 执行返回信息
  23.      /// </summary>
  24.      public string ReturnMessage
  25.      {
  26.          get{return _ReturnMessage;}
  27.      }
  28.  
  29.      public ExcelIO()
  30.      {
  31.      }
  32.  
  33.      /// <summary>
  34.      /// 导入EXCEL到DataSet
  35.      /// </summary>
  36.      /// <param name="fileName">Excel全路径文件名</param>
  37.      /// <returns>导入成功的DataSet</returns>
  38.      public DataSet ImportExcel(string fileName)
  39.      {
  40.          //判断是否安装EXCEL
  41.          Excel.Application xlApp=new Excel.ApplicationClass();          
  42.          if(xlApp==null)
  43.          {
  44.              _ReturnStatus = -1;
  45.              _ReturnMessage = "无法创建Excel对象,可能您的计算机未安装Excel";
  46.              return null;
  47.          }      
  48.  
  49.          //判断文件是否被其他进程使用            
  50.          Excel.Workbook workbook;                
  51.          try
  52.          {
  53.              workbook = xlApp.Workbooks.Open(fileName,0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, 1, 0);
  54.          }
  55.          catch
  56.          {
  57.              _ReturnStatus = -1;
  58.              _ReturnMessage = "Excel文件处于打开状态,请保存关闭";
  59.              return null;
  60.          }      
  61.        
  62.          //获得所有Sheet名称
  63.          int n = workbook.Worksheets.Count;
  64.          string[] SheetSet = new string[n];
  65.          System.Collections.ArrayList al = new System.Collections.ArrayList();
  66.          for(int i=1; i<=n; i++)
  67.          {
  68.              SheetSet[i-1] = ((Excel.Worksheet)workbook.Worksheets[i]).Name;
  69.          }
  70.        
  71.          //释放Excel相关对象
  72.          workbook.Close(null,null,null);        
  73.          xlApp.Quit();
  74.          if(workbook != null)
  75.          {
  76.              System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
  77.              workbook = null;
  78.          }
  79.          if(xlApp != null)
  80.          {
  81.              System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
  82.              xlApp = null;
  83.          }  
  84.          GC.Collect();
  85.        
  86.          //把EXCEL导入到DataSet
  87.          DataSet ds = new DataSet();        
  88.          string connStr = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = "+ fileName +";Extended Properties=Excel 8.0" ;
  89.          using(OleDbConnection conn = new OleDbConnection (connStr))
  90.          {
  91.              conn.Open();
  92.              OleDbDataAdapter da;
  93.              for(int i=1; i<=n; i++)
  94.              {
  95.                  string sql = "select * from ["+ SheetSet[i-1] +"$] ";
  96.                  da = new OleDbDataAdapter(sql,conn);
  97.                  da.Fill(ds,SheetSet[i-1]);  
  98.                  da.Dispose();
  99.              }              
  100.              conn.Close();
  101.              conn.Dispose();
  102.          }              
  103.          return ds;
  104.      }
  105.  
  106.      /// <summary>
  107.      /// 把DataTable导出到EXCEL
  108.      /// </summary>
  109.      /// <param name="reportName">报表名称</param>
  110.      /// <param name="dt">数据源表</param>
  111.      /// <param name="saveFileName">Excel全路径文件名</param>
  112.      /// <returns>导出是否成功</returns>
  113.      public bool ExportExcel(string reportName,DataTable dt,string saveFileName)
  114.      {
  115.          if(dt==null)
  116.          {
  117.              _ReturnStatus = -1;
  118.              _ReturnMessage = "数据集为空!";
  119.              return false;          
  120.          }
  121.  
  122.          bool fileSaved=false;
  123.          Excel.Application xlApp=new Excel.ApplicationClass();  
  124.          if(xlApp==null)
  125.          {
  126.              _ReturnStatus = -1;
  127.              _ReturnMessage = "无法创建Excel对象,可能您的计算机未安装Excel";
  128.              return false;
  129.          }
  130.  
  131.          Excel.Workbooks workbooks=xlApp.Workbooks;
  132.          Excel.Workbook workbook=workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
  133.          Excel.Worksheet worksheet=(Excel.Worksheet)workbook.Worksheets[1];//取得sheet1
  134.          worksheet.Cells.Font.Size = 10;
  135.          Excel.Range range;
  136.  
  137.          long totalCount=dt.Rows.Count;
  138.          long rowRead=0;
  139.          float percent=0;
  140.  
  141.          worksheet.Cells[1,1]=reportName;
  142.          ((Excel.Range)worksheet.Cells[1,1]).Font.Size = 12;
  143.          ((Excel.Range)worksheet.Cells[1,1]).Font.Bold = true;
  144.  
  145.          //写入字段
  146.          for(int i=0;i<dt.Columns.Count;i++)
  147.          {
  148.              worksheet.Cells[2,i+1]=dt.Columns[i].ColumnName;
  149.              range=(Excel.Range)worksheet.Cells[2,i+1];
  150.              range.Interior.ColorIndex = 15;
  151.              range.Font.Bold = true;
  152.  
  153.          }
  154.          //写入数值
  155.          for(int r=0;r<dt.Rows.Count;r++)
  156.          {
  157.              for(int i=0;i<dt.Columns.Count;i++)
  158.              {
  159.                  worksheet.Cells[r+3,i+1]=dt.Rows[r][i].ToString();
  160.              }
  161.              rowRead++;
  162.              percent=((float)(100*rowRead))/totalCount;
  163.          }
  164.        
  165.          range=worksheet.get_Range(worksheet.Cells[2,1],worksheet.Cells[dt.Rows.Count+2,dt.Columns.Count]);
  166.          range.BorderAround(Excel.XlLineStyle.xlContinuous,Excel.XlBorderWeight.xlThin,Excel.XlColorIndex.xlColorIndexAutomatic,null);
  167.          if( dt.Rows.Count > 0)
  168.          {
  169.              range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].ColorIndex = Excel.XlColorIndex.xlColorIndexAutomatic;
  170.              range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].LineStyle =Excel.XlLineStyle.xlContinuous;
  171.              range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].Weight =Excel.XlBorderWeight.xlThin;
  172.          }
  173.          if(dt.Columns.Count>1)
  174.          {
  175.              range.Borders[Excel.XlBordersIndex.xlInsideVertical].ColorIndex =Excel.XlColorIndex.xlColorIndexAutomatic;
  176.              range.Borders[Excel.XlBordersIndex.xlInsideVertical].LineStyle = Excel.XlLineStyle.xlContinuous;
  177.              range.Borders[Excel.XlBordersIndex.xlInsideVertical].Weight = Excel.XlBorderWeight.xlThin;
  178.          }
  179.  
  180.          //保存文件
  181.          if(saveFileName!="")
  182.          {
  183.              try
  184.              {
  185.                  workbook.Saved =true;
  186.                  workbook.SaveCopyAs(saveFileName);
  187.                  fileSaved=true;
  188.              }
  189.              catch(Exception ex)
  190.              {
  191.                  fileSaved=false;
  192.                  _ReturnStatus = -1;
  193.                  _ReturnMessage = "导出文件时出错,文件可能正被打开!\n"+ex.Message;
  194.              }
  195.          }
  196.          else
  197.          {
  198.              fileSaved=false;
  199.          }          
  200.    
  201.          //释放Excel对应的对象
  202.          if(range != null)
  203.          {
  204.              System.Runtime.InteropServices.Marshal.ReleaseComObject(range);
  205.              range = null;
  206.          }
  207.          if(worksheet != null)
  208.          {
  209.              System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
  210.              worksheet = null;
  211.          }
  212.          if(workbook != null)
  213.          {
  214.              System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
  215.              workbook = null;
  216.          }
  217.          if(workbooks != null)
  218.          {
  219.              System.Runtime.InteropServices.Marshal.ReleaseComObject(workbooks);
  220.              workbooks = null;
  221.          }              
  222.          xlApp.Application.Workbooks.Close();
  223.          xlApp.Quit();
  224.          if(xlApp != null)
  225.          {
  226.              System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
  227.              xlApp = null;
  228.          }
  229.          GC.Collect();
  230.          return fileSaved;
  231.      }
  232. }
  233. //csharp/7261

回复 "C#导入导出数据到Excel的通用类代码"

这儿你可以回复上面这条便签

captcha