C# Excel 解决方案

 C# Excel 解决方案

因为现在用到的是winform,对web的解决没有去关注,所以现在只是对winform操作excel做笔记

以前做考试系统的时候,接触过excel导入,不过当时不是我负责所以了解不多,只是知道在.net中excel可以想其他数据源一样访问。

 

C# 操作Excel分两种情况

1.利用office组件,就是要安装office(或者下载dll添加引用也可以,没试过) 。代码1

 

2.不利用office组件,而是用TextWriter的某些子类编写器将字节流写入文件,这些文件其实不是真正的excel文件(可以用记事本打开不乱码),虽然能用excel打开。如果你在把这些导出的文件当作excel数据源,就不行了。

 

    其实还有一种方法虽然不利用office组件不过当导出到excel的时候有有一个事先创建好的excel文件(这样比用office组件好点,毕竟有别的编译器可以生成excel文件,不过这样也只是自欺欺人吧)。这个方法是导出的时候也把已经创建好的excel当做数据源用OleDbCommand.ExecuteNonQuery()等方法写入excel。我们把这标记为代码3,以便下面提供代码。

 

相关代码:

我们先看最后一种方法代码(我开始用的是这个不上不下的方法)

代码3

  1.         /// <summary>
  2.         /// 将DataTable导出为excel 自动创建excel
  3.         /// </summary>
  4.         /// <param name="dt"> 数据源</param>
  5.         /// <param name="ExcelFileName"> 要保存的excel的name</param>
  6.         /// <param name="strWorkSheetName">创建的表的名字 </param>
  7.         public static string ExportTable2ExcelFile(DataTable dt, string ExcelFileName, string strWorkSheetName)
  8.         {
  9.             if (File.Exists(ExcelFileName) == false)
  10.             {
  11.                 return "指定文件不存在!";
  12.             }
  13.             if (dt == null)
  14.             {
  15.                 return "数据不能为空!";
  16.             }
  17.             if (strWorkSheetName.ToString() == "")
  18.             {
  19.                 return "数据表名不可以为空!";
  20.             }
  21.             dt.TableName = strWorkSheetName;
  22.             int iRows = dt.Rows.Count;
  23.             int iCols = dt.Columns.Count;
  24.             StringBuilder stringBuilder;
  25.             string connString;
  26.             if (iRows == 0)
  27.             {
  28.                 return "没有可导入数据!";
  29.             }
  30.             stringBuilder = new StringBuilder();
  31.             connString = ExcelOperation.GetExcelConnection(ExcelFileName);// "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ExcelFileName + ";Extended Properties=Excel 8.0;";
  32.             //先查看此Excel中是否有相关Table,如果有的话就删除,然后导入新的。
  33.             //生成创建表的脚本
  34.             stringBuilder.Append("CREATE TABLE ");
  35.             stringBuilder.Append(dt.TableName + " ( ");
  36.             for (int i = 0; i < iCols; i++)
  37.             {
  38.                 //此处是本版本改进中最实用的地方
  39.                 string strType = ExcelOperation.GetOleDataType(dt.Columns[i]);
  40.                 if (i < iCols - 1)
  41.                     stringBuilder.Append(string.Format("{0} {1},", dt.Columns[i].ColumnName, strType));
  42.                 else
  43.                     stringBuilder.Append(string.Format("{0} {1})", dt.Columns[i].ColumnName, strType));
  44.             }
  45.             using (OleDbConnection objConn = new OleDbConnection(connString))
  46.             {
  47.                 OleDbCommand objCmd = new OleDbCommand();
  48.                 objCmd.Connection = objConn;
  49.                 //插入新表
  50.                 objCmd.CommandText = stringBuilder.ToString();
  51.                 try
  52.                 {
  53.                     objConn.Open();
  54.                     //插入新表
  55.                     objCmd.ExecuteNonQuery();
  56.                 }
  57.                 catch (Exception e)
  58.                 {
  59.                     return "在Excel中创建表失败!错误信息:" + e.Message;
  60.                 }
  61.                 stringBuilder.Remove(0, stringBuilder.Length);
  62.                 stringBuilder.Append("INSERT INTO ");
  63.                 stringBuilder.Append(dt.TableName + " ( ");
  64.                 //先插入标头
  65.                 for (int i = 0; i < iCols; i++)
  66.                 {
  67.                     if (i < iCols - 1)
  68.                         stringBuilder.Append(dt.Columns[i].ColumnName + ",");
  69.                     else
  70.                         stringBuilder.Append(dt.Columns[i].ColumnName + ") values (");
  71.                 }
  72.                 for (int i = 0; i < iCols; i++)
  73.                 {
  74.                     if (i < iCols - 1)
  75.                         stringBuilder.Append("@" + dt.Columns[i].ColumnName + ",");
  76.                     else
  77.                         stringBuilder.Append("@" + dt.Columns[i].ColumnName + ")");
  78.                 }
  79.                 //建立插入动作的Command
  80.                 objCmd.CommandText = stringBuilder.ToString();
  81.                 OleDbParameterCollection oleParam = objCmd.Parameters;
  82.                 oleParam.Clear();
  83.                 for (int i = 0; i < iCols; i++)
  84.                 {
  85.                     OleDbType oleDbType = ExcelOperation.GetRefOleDataType(dt.Columns[i]);
  86.                     //此处是本版本改进中最实用的地方
  87.                     oleParam.Add(new OleDbParameter("@" + dt.Columns[i].ColumnName, oleDbType));
  88.                 }
  89.                 //遍历DataTable将数据插入新建的Excel文件中
  90.                 foreach (DataRow row in dt.Rows)
  91.                 {
  92.                     for (int i = 0; i < oleParam.Count; i++)
  93.                     {
  94.                         oleParam[i].Value = row[i];
  95.                     }
  96.                     objCmd.ExecuteNonQuery();
  97.                 }
  98.                 return "数据已成功导入Excel!";
  99.             }
  100.         }
  101.         /// <summary>
  102.         /// 获取与本地DataSet中指定列的类型对应的OleDbType的数据类型字符串
  103.         /// </summary>
  104.         /// <param name="dataColumn"></param>
  105.         /// <returns></returns>
  106.         public static string GetOleDataType(DataColumn dataColumn)
  107.         {
  108.             switch (dataColumn.DataType.Name)
  109.             {
  110.                 case "String"://字符串
  111.                     {
  112.                         return "VarChar";
  113.                     }
  114.                 case "Double"://数字
  115.                     {
  116.                         return "Double";
  117.                     }
  118.                 case "Decimal"://数字
  119.                     {
  120.                         return "Decimal";
  121.                     }
  122.                 case "DateTime"://时间
  123.                     {
  124.                         return "Date";
  125.                     }
  126.                 default://
  127.                     {
  128.                         return "VarChar";
  129.                     }
  130.             }
  131.         }
  132.         /// <summary>
  133.         /// 获取与本地DataSet中指定列的类型对应的OleDbType类型
  134.         /// </summary>
  135.         /// <param name="dataColumn"></param>
  136.         /// <returns></returns>
  137.         public static OleDbType GetRefOleDataType(DataColumn dataColumn)
  138.         {
  139.             switch (dataColumn.DataType.Name)
  140.             {
  141.                 case "String"://字符串
  142.                     {
  143.                         return OleDbType.VarChar;
  144.                     }
  145.                 case "Double"://数字
  146.                     {
  147.                         return OleDbType.Double;
  148.                     }
  149.                 case "Decimal"://数字
  150.                     {
  151.                         return OleDbType.Decimal;
  152.                     }
  153.                 case "DateTime"://时间
  154.                     {
  155.                         return OleDbType.Date;
  156.                     }
  157.                 default:
  158.                     {
  159.                         return OleDbType.VarChar;
  160.                     }
  161.             }
  162.         }
  163.         public static string GetExcelConnection(string strFilePath)
  164.         {
  165.             if (!File.Exists(strFilePath))
  166.             {
  167.                 throw new Exception("指定的Excel文件不存在!");
  168.             }
  169.             return
  170.                  @"Provider=Microsoft.Jet.OLEDB.4.0;" +
  171.                  @"Data Source=" + strFilePath + ";" +
  172.                  @"Extended Properties=" + Convert.ToChar(34).ToString() +
  173.                  @"Excel 8.0;" + "Imex=2;HDR=Yes;" + Convert.ToChar(34).ToString();
  174.         }

2.不利用office组件,而是用TextWriter的某些子类编写器将字节流写入文件。

这个提供一个类库的使用吧,就不发代码了4百多行,可以到下面的网址去下。项目是vs2003做的要转换下然后把RKLib.ExportData.dll复制到bin下引用(或直接引用)然后就可以直接用了

导出到excel的代码:  RKLib.ExportData.Export objExport = new RKLib.ExportData.Export("Win");
                                     objExport.ExportDetails(dt, Export.ExportFormat.Excel, saveFileDialog1.FileName);

这个还提供了web导出和CSV格式导出。

 

网址:http://www.codeproject.com/KB/aspnet/ExportClassLibrary.aspx

 

 

利用office组件。这类代码网上很多。

代码1:

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

参考:

3.http://dr.net.blog.163.com/blog/static/226451372007621082489/

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值