DataSet导出到Excel比较完整的解决方案 二 --服务器端生成文件 downmoon

分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow

也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!

               

前一篇文章中,介绍了DataSet导出到Excel时客户端生成文件的几种思路,接着往下说,服务器端生成文件,用户直接下载,应该格式是可以保证的!

于是直接调用Excel的API生成。代码如下:

[c-sharp] view plain copy print ?
  1. public static void DataSetToLocalExcel(DataSet dataSet, string outputPath, bool deleteOldFile)  
  2.        {  
  3.            if (deleteOldFile)  
  4.            {  
  5.                if (System.IO.File.Exists(outputPath)) { System.IO.File.Delete(outputPath); }  
  6.            }  
  7.            // Create the Excel Application object  
  8.            ApplicationClass excelApp = new ApplicationClass();  
  9.            // Create a new Excel Workbook  
  10.            Workbook excelWorkbook = excelApp.Workbooks.Add(Type.Missing);  
  11.            int sheetIndex = 0;  
  12.            // Copy each DataTable  
  13.            foreach (System.Data.DataTable dt in dataSet.Tables)  
  14.            {  
  15.                // Copy the DataTable to an object array  
  16.                object[,] rawData = new object[dt.Rows.Count + 1, dt.Columns.Count];  
  17.                // Copy the column names to the first row of the object array  
  18.                for (int col = 0; col < dt.Columns.Count; col++)  
  19.                {  
  20.                    rawData[0, col] = dt.Columns[col].ColumnName;  
  21.                }  
  22.                // Copy the values to the object array  
  23.                for (int col = 0; col < dt.Columns.Count; col++)  
  24.                {  
  25.                    for (int row = 0; row < dt.Rows.Count; row++)  
  26.                    {  
  27.                        rawData[row + 1, col] = dt.Rows[row].ItemArray[col];  
  28.                    }  
  29.                }  
  30.                // Calculate the final column letter  
  31.                string finalColLetter = string.Empty;  
  32.                string colCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";  
  33.                int colCharsetLen = colCharset.Length;  
  34.                if (dt.Columns.Count > colCharsetLen)  
  35.                {  
  36.                    finalColLetter = colCharset.Substring(  
  37.                        (dt.Columns.Count - 1) / colCharsetLen - 1, 1);  
  38.                }  
  39.                finalColLetter += colCharset.Substring(  
  40.                        (dt.Columns.Count - 1) % colCharsetLen, 1);  
  41.                // Create a new Sheet  
  42.                Worksheet excelSheet = (Worksheet)excelWorkbook.Sheets.Add(  
  43.                    excelWorkbook.Sheets.get_Item(++sheetIndex),  
  44.                    Type.Missing, 1, XlSheetType.xlWorksheet);  
  45.                excelSheet.Name = dt.TableName;  
  46.                // Fast data export to Excel  
  47.                string excelRange = string.Format("A1:{0}{1}",  
  48.                    finalColLetter, dt.Rows.Count + 1);  
  49.                excelSheet.get_Range(excelRange, Type.Missing).Value2 = rawData;  
  50.                // Mark the first row as BOLD  
  51.                ((Range)excelSheet.Rows[1, Type.Missing]).Font.Bold = true;  
  52.            }  
  53.            //excelApp.Application.AlertBeforeOverwriting = false;  
  54.            excelApp.Application.DisplayAlerts = false;  
  55.            // Save and Close the Workbook  
  56.            excelWorkbook.SaveAs(outputPath, XlFileFormat.xlWorkbookNormal, Type.Missing,  
  57.                Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlExclusive,  
  58.                Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);  
  59.            excelWorkbook.Close(true, Type.Missing, Type.Missing);  
  60.            excelWorkbook = null;  
  61.            // Release the Application object  
  62.            excelApp.Quit();  
  63.            excelApp = null;  
  64.            // Collect the unreferenced objects  
  65.            GC.Collect();  
  66.            GC.WaitForPendingFinalizers();  
  67.        }  
public static void DataSetToLocalExcel(DataSet dataSet, string outputPath, bool deleteOldFile)        {            if (deleteOldFile)            {                if (System.IO.File.Exists(outputPath)) { System.IO.File.Delete(outputPath); }            }            // Create the Excel Application object            ApplicationClass excelApp = new ApplicationClass();            // Create a new Excel Workbook            Workbook excelWorkbook = excelApp.Workbooks.Add(Type.Missing);            int sheetIndex = 0;            // Copy each DataTable            foreach (System.Data.DataTable dt in dataSet.Tables)            {                // Copy the DataTable to an object array                object[,] rawData = new object[dt.Rows.Count + 1, dt.Columns.Count];                // Copy the column names to the first row of the object array                for (int col = 0; col < dt.Columns.Count; col++)                {                    rawData[0, col] = dt.Columns[col].ColumnName;                }                // Copy the values to the object array                for (int col = 0; col < dt.Columns.Count; col++)                {                    for (int row = 0; row < dt.Rows.Count; row++)                    {                        rawData[row + 1, col] = dt.Rows[row].ItemArray[col];                    }                }                // Calculate the final column letter                string finalColLetter = string.Empty;                string colCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";                int colCharsetLen = colCharset.Length;                if (dt.Columns.Count > colCharsetLen)                {                    finalColLetter = colCharset.Substring(                        (dt.Columns.Count - 1) / colCharsetLen - 1, 1);                }                finalColLetter += colCharset.Substring(                        (dt.Columns.Count - 1) % colCharsetLen, 1);                // Create a new Sheet                Worksheet excelSheet = (Worksheet)excelWorkbook.Sheets.Add(                    excelWorkbook.Sheets.get_Item(++sheetIndex),                    Type.Missing, 1, XlSheetType.xlWorksheet);                excelSheet.Name = dt.TableName;                // Fast data export to Excel                string excelRange = string.Format("A1:{0}{1}",                    finalColLetter, dt.Rows.Count + 1);                excelSheet.get_Range(excelRange, Type.Missing).Value2 = rawData;                // Mark the first row as BOLD                ((Range)excelSheet.Rows[1, Type.Missing]).Font.Bold = true;            }            //excelApp.Application.AlertBeforeOverwriting = false;            excelApp.Application.DisplayAlerts = false;            // Save and Close the Workbook            excelWorkbook.SaveAs(outputPath, XlFileFormat.xlWorkbookNormal, Type.Missing,                Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlExclusive,                Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);            excelWorkbook.Close(true, Type.Missing, Type.Missing);            excelWorkbook = null;            // Release the Application object            excelApp.Quit();            excelApp = null;            // Collect the unreferenced objects            GC.Collect();            GC.WaitForPendingFinalizers();        }

说明下,其中的  xlsApp.Application.DisplayAlerts   =   false;  的作用是不显示确认对话框    

也可以逐Cell读取,那样可能会慢。本方法速度还过得去。

生成Winform代码测试没错,部署时,以为只要引用两个dll就可以了

Microsoft.Office.Interop.Excel.dll

Office.dll

那成想,问题接着来了,当在WebForm下调用时, 提示检索   COM   类工厂中   CLSID   为   {00024500-0000-0000-C000-000000000046}   的组件时失败,原因是出现以下错误:   8000401a ”

晕! Google下,解决方案是在服务器上安装Office,并配置DCOM权限。步骤如下:

  1. 配置  DCOM  中  EXCEL  应用程序:  
  2. 要在交互式用户帐户下设置  Office  自动化服务器,请按照下列步骤操作:   
  3. 1.  以管理员身份登录到计算机,并使用完整安装来安装(或重新安装)Office。为了实现系统的可靠性,建议您将  Office  CD-ROM  中的内容复制到本地驱动器并从此位置安装  Office。   
  4. 2.  启动要自动运行的  Office  应用程序。这会强制该应用程序进行自我注册。   
  5. 3.  运行该应用程序后,请按  Alt+F11  以加载  Microsoft  Visual  Basic  for  Applications  (VBA)  编辑器。这会强制  VBA  进行初始化。   
  6. 4.  关闭应用程序,包括  VBA。   
  7. 5.  单击开始,单击运行,然后键入  DCOMCNFG。选择要自动运行的应用程序。应用程序名称如下所示:   
  8. Microsoft  Access  97  -  Microsoft  Access  数据库  
  9. Microsoft  Access  2000/2002  -  Microsoft  Access  应用程序  
  10. Microsoft  Excel  97/2000/2002  -  Microsoft  Excel  应用程序  
  11. Microsoft  Word  97  -  Microsoft  Word  Basic  
  12. Microsoft  Word  2000/2002  -  Microsoft  Word  文档   
  13. 单击属性打开此应用程序的属性对话框。  
  14. 6.  单击安全选项卡。验证使用默认的访问权限和使用默认的启动权限已选中。   
  15. 7.  单击标识选项卡,然后选择交互式用户。   
  16. 8.  单击确定,关闭属性对话框并返回主应用程序列表对话框。   
  17. 9.  在  DCOM  配置对话框中,单击默认安全性选项卡。   
  18. 10.  单击访问权限的编辑默认值。验证访问权限中是否列出下列用户,如果没有列出,则添加这些用户:   
  19. SYSTEM  
  20. INTERACTIVE  
  21. Everyone  
  22. Administrators  
  23. IUSR_ <machinename> *  
  24. IWAM_ <machinename> *  
  25. *  这些帐户仅在计算机上安装了  Internet  Information  Server  (IIS)  的情况下才存在。   
  26. 11.  确保允许每个用户访问,然后单击确定。   
  27. 12.  单击启动权限的编辑默认值。验证启动权限中是否列出下列用户,如果没有列出,则添加这些用户:   
  28. SYSTEM  
  29. INTERACTIVE  
  30. Everyone  
  31. Administrators  
  32. IUSR_ <machinename> *  
  33. IWAM_ <machinename> *  
  34. *  这些帐户仅在计算机上安装有  IIS  的情况下才存在。   
  35. 13.  确保允许每个用户访问,然后单击确定。   
  36. 14.  单击确定关闭  DCOMCNFG。   
  37. 如果你之前起用了身份模拟  (在  web.config  中配置了  <identity  impersonate= "true "/>  )  ,需要删除之!   
  38. 15.更新安装office,把.net可编程组件安装到本机(excel组件)  
  39. 如果还是不行.干脃把交互式用户 换成"启动用户"   
配置  DCOM  中  EXCEL  应用程序:要在交互式用户帐户下设置  Office  自动化服务器,请按照下列步骤操作: 1.  以管理员身份登录到计算机,并使用完整安装来安装(或重新安装)Office。为了实现系统的可靠性,建议您将  Office  CD-ROM  中的内容复制到本地驱动器并从此位置安装  Office。 2.  启动要自动运行的  Office  应用程序。这会强制该应用程序进行自我注册。 3.  运行该应用程序后,请按  Alt+F11  以加载  Microsoft  Visual  Basic  for  Applications  (VBA)  编辑器。这会强制  VBA  进行初始化。 4.  关闭应用程序,包括  VBA。 5.  单击开始,单击运行,然后键入  DCOMCNFG。选择要自动运行的应用程序。应用程序名称如下所示: Microsoft  Access  97  -  Microsoft  Access  数据库Microsoft  Access  2000/2002  -  Microsoft  Access  应用程序Microsoft  Excel  97/2000/2002  -  Microsoft  Excel  应用程序Microsoft  Word  97  -  Microsoft  Word  BasicMicrosoft  Word  2000/2002  -  Microsoft  Word  文档 单击属性打开此应用程序的属性对话框。6.  单击安全选项卡。验证使用默认的访问权限和使用默认的启动权限已选中。 7.  单击标识选项卡,然后选择交互式用户。 8.  单击确定,关闭属性对话框并返回主应用程序列表对话框。 9.  在  DCOM  配置对话框中,单击默认安全性选项卡。 10.  单击访问权限的编辑默认值。验证访问权限中是否列出下列用户,如果没有列出,则添加这些用户: SYSTEMINTERACTIVEEveryoneAdministratorsIUSR_ <machinename> *IWAM_ <machinename> **  这些帐户仅在计算机上安装了  Internet  Information  Server  (IIS)  的情况下才存在。 11.  确保允许每个用户访问,然后单击确定。 12.  单击启动权限的编辑默认值。验证启动权限中是否列出下列用户,如果没有列出,则添加这些用户: SYSTEMINTERACTIVEEveryoneAdministratorsIUSR_ <machinename> *IWAM_ <machinename> **  这些帐户仅在计算机上安装有  IIS  的情况下才存在。 13.  确保允许每个用户访问,然后单击确定。 14.  单击确定关闭  DCOMCNFG。 如果你之前起用了身份模拟  (在  web.config  中配置了  <identity  impersonate= "true "/>  )  ,需要删除之! 15.更新安装office,把.net可编程组件安装到本机(excel组件)如果还是不行.干脃把交互式用户 换成"启动用户"

折腾了一番,总算可以用了!·只是服务器上装Office总感觉不爽,于是再尝试下别的方法:

Reading and Writing Excel using OLEDB

主要的类文件如下:

[c-sharp] view plain copy print ?
  1. /**//// <summary>  
  2.     /// Summary description for ExcelReader.  
  3.     /// </summary>  
  4.     public class ExcelReader : IDisposable  
  5.     {  
  6.         Variables#region Variables  
  7.         private int[] _PKCol;  
  8.         private string _strExcelFilename;  
  9.         private bool _blnMixedData = true;  
  10.         private bool _blnHeaders = false;  
  11.         private string _strSheetName;  
  12.         private string _strSheetRange;  
  13.         private bool _blnKeepConnectionOpen = false;  
  14.         private OleDbConnection _oleConn;  
  15.         private OleDbCommand _oleCmdSelect;  
  16.         private OleDbCommand _oleCmdUpdate;  
  17.         #endregion  
  18.         properties#region properties  
  19.         public int[] PKCols  
  20.         {  
  21.             get { return _PKCol; }  
  22.             set { _PKCol = value; }  
  23.         }  
  24.         public string ColName(int intCol)  
  25.         {  
  26.             string sColName = "";  
  27.             if (intCol < 26)  
  28.                 sColName = Agronet.Common.Framework.Util.SQLParser.StringParse(Convert.ToChar((Convert.ToByte((char)'A') + intCol)));  
  29.             else  
  30.             {  
  31.                 int intFirst = ((int)intCol / 26);  
  32.                 int intSecond = ((int)intCol % 26);  
  33.                 sColName = Agronet.Common.Framework.Util.SQLParser.StringParse(Convert.ToByte((char)'A') + intFirst);  
  34.                 sColName += Agronet.Common.Framework.Util.SQLParser.StringParse(Convert.ToByte((char)'A') + intSecond);  
  35.             }  
  36.             return sColName;  
  37.         }  
  38.         public int ColNumber(string strCol)  
  39.         {  
  40.             strCol = strCol.ToUpper();  
  41.             int intColNumber = 0;  
  42.             if (strCol.Length > 1)  
  43.             {  
  44.                 intColNumber = Agronet.Common.Framework.Util.SQLParser.ShortParse(Convert.ToByte(strCol[1]) - 65);  
  45.                 intColNumber += Agronet.Common.Framework.Util.SQLParser.ShortParse(Convert.ToByte(strCol[1]) - 64) * 26;  
  46.             }  
  47.             else  
  48.                 intColNumber = Agronet.Common.Framework.Util.SQLParser.ShortParse(Convert.ToByte(strCol[0]) - 65);  
  49.             return intColNumber;  
  50.         }  
  51.         public String[] GetExcelSheetNames()  
  52.         {  
  53.             System.Data.DataTable dt = null;  
  54.             try  
  55.             {  
  56.                 if (_oleConn == null) Open();  
  57.                 // Get the data table containing the schema  
  58.                 dt = _oleConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);  
  59.                 if (dt == null) { return null; }  
  60.                 String[] excelSheets = new String[dt.Rows.Count];  
  61.                 int i = 0;  
  62.                 // Add the sheet name to the string array.  
  63.                 foreach (DataRow row in dt.Rows)  
  64.                 {  
  65.                     string strSheetTableName = row["TABLE_NAME"].ToString();  
  66.                     excelSheets[i] = strSheetTableName.Substring(0, strSheetTableName.Length - 1);  
  67.                     i++;  
  68.                 }  
  69.                 return excelSheets;  
  70.             }  
  71.             catch (Exception ex)//tony 2008.12.31 update  
  72.             {  
  73.                 string s = ex.Message; return null;  
  74.             }  
  75.             finally  
  76.             {  
  77.                 // Clean up.  
  78.                 if (this.KeepConnectionOpen == false)  
  79.                 {  
  80.                     this.Close();  
  81.                 }  
  82.                 if (dt != null)  
  83.                 {  
  84.                     dt.Dispose();  
  85.                     dt = null;  
  86.                 }  
  87.             }  
  88.         }  
  89.         public string ExcelFilename  
  90.         {  
  91.             get { return _strExcelFilename; }  
  92.             set { _strExcelFilename = value; }  
  93.         }  
  94.         public string SheetName  
  95.         {  
  96.             get { return _strSheetName; }  
  97.             set { _strSheetName = value; }  
  98.         }  
  99.         public string SheetRange  
  100.         {  
  101.             get { return _strSheetRange; }  
  102.             set  
  103.             {  
  104.                 if (value.IndexOf(":") == -1) throw new Exception("Invalid range length");  
  105.                 _strSheetRange = value;  
  106.             }  
  107.         }  
  108.         public bool KeepConnectionOpen  
  109.         {  
  110.             get { return _blnKeepConnectionOpen; }  
  111.             set { _blnKeepConnectionOpen = value; }  
  112.         }  
  113.         public bool Headers  
  114.         {  
  115.             get { return _blnHeaders; }  
  116.             set { _blnHeaders = value; }  
  117.         }  
  118.         public bool MixedData  
  119.         {  
  120.             get { return _blnMixedData; }  
  121.             set { _blnMixedData = value; }  
  122.         }  
  123.         #endregion  
  124.         Methods#region Methods  
  125.         Excel Connection#region Excel Connection  
  126.         private string ExcelConnectionOptions()  
  127.         {  
  128.             string strOpts = "";  
  129.             if (this.MixedData == true)  
  130.                 strOpts += "Imex=1;";  
  131.             if (this.Headers == true)  
  132.                 strOpts += "HDR=Yes;";  
  133.             else  
  134.                 strOpts += "HDR=No;";  
  135.             return strOpts;  
  136.         }  
  137.         private string ExcelConnection()  
  138.         {  
  139.             return  
  140.                 @"Provider=Microsoft.Jet.OLEDB.4.0;" +  
  141.                 @"Data Source=" + _strExcelFilename + ";" +  
  142.                 @"Extended Properties=" + Convert.ToChar(34).ToString() +  
  143.                 @"Excel 8.0;" + ExcelConnectionOptions() + Convert.ToChar(34).ToString();  
  144.         }  
  145.         #endregion  
  146.         Open / Close#region Open / Close  
  147.         public void Open()  
  148.         {  
  149.             try  
  150.             {  
  151.                 if (_oleConn != null)  
  152.                 {  
  153.                     if (_oleConn.State == ConnectionState.Open)  
  154.                     {  
  155.                         _oleConn.Close();  
  156.                     }  
  157.                     _oleConn = null;  
  158.                 }  
  159.                 if (System.IO.File.Exists(_strExcelFilename) == false)  
  160.                 {  
  161.                     throw new Exception("Excel file " + _strExcelFilename + "could not be found.");  
  162.                 }  
  163.                 _oleConn = new OleDbConnection(ExcelConnection());  
  164.                 _oleConn.Open();  
  165.             }  
  166.             catch (Exception ex)  
  167.             {  
  168.                 throw ex;  
  169.             }  
  170.         }  
  171.         public void Close()  
  172.         {  
  173.             if (_oleConn != null)  
  174.             {  
  175.                 if (_oleConn.State != ConnectionState.Closed)  
  176.                     _oleConn.Close();  
  177.                 _oleConn.Dispose();  
  178.                 _oleConn = null;  
  179.             }  
  180.         }  
  181.         #endregion  
  182.         Command Select#region Command Select  
  183.         private bool SetSheetQuerySelect()  
  184.         {  
  185.             try  
  186.             {  
  187.                 if (_oleConn == null)  
  188.                 {  
  189.                     throw new Exception("Connection is unassigned or closed.");  
  190.                 }  
  191.                 if (_strSheetName.Length == 0)  
  192.                     throw new Exception("Sheetname was not assigned.");  
  193.                 /**//* 
  194.                                 string tmpStr=@"SELECT * FROM ["  
  195.                                     + _strSheetName  
  196.                                     + "$" + _strSheetRange 
  197.                                     + "]"; 
  198.                 */  
  199.                 //System.Windows.Forms.MessageBox.Show(tmpStr);  
  200.                 //if(_strSheetName.EndsWith("$")){_strSheetName=_strSheetName.TrimEnd('$');}  
  201.                 _oleCmdSelect = new OleDbCommand(  
  202.                     @"SELECT * FROM ["  
  203.                     + _strSheetName  
  204.                     + "$" //+ _strSheetRange  
  205.                     + "]", _oleConn);  
  206.                 //me  
  207.                 return true;  
  208.             }  
  209.             catch (Exception ex)  
  210.             {  
  211.                 throw ex;  
  212.             }  
  213.         }  
  214.         #endregion  
  215.         simple utilities#region simple utilities  
  216.         private string AddWithComma(string strSource, string strAdd)  
  217.         {  
  218.             if (strSource != "") strSource = strSource += ", ";  
  219.             return strSource + strAdd;  
  220.         }  
  221.         private string AddWithAnd(string strSource, string strAdd)  
  222.         {  
  223.             if (strSource != "") strSource = strSource += " and ";  
  224.             return strSource + strAdd;  
  225.         }  
  226.         #endregion  
  227.         private OleDbDataAdapter SetSheetQueryAdapter(DataTable dt)  
  228.         {  
  229.             // Deleting in Excel workbook is not possible  
  230.             //So this command is not defined  
  231.             try  
  232.             {  
  233.                 if (_oleConn == null)  
  234.                 {  
  235.                     throw new Exception("Connection is unassigned or closed.");  
  236.                 }  
  237.                 if (_strSheetName.Length == 0)  
  238.                     throw new Exception("Sheetname was not assigned.");  
  239.                 if (PKCols == null)  
  240.                     throw new Exception("Cannot update excel sheet with no primarykey set.");  
  241.                 if (PKCols.Length < 1)  
  242.                     throw new Exception("Cannot update excel sheet with no primarykey set.");  
  243.                 OleDbDataAdapter oleda = new OleDbDataAdapter(_oleCmdSelect);  
  244.                 string strUpdate = "";  
  245.                 string strInsertPar = "";  
  246.                 string strInsert = "";  
  247.                 string strWhere = "";  
  248.                 for (int iPK = 0; iPK < PKCols.Length; iPK++)  
  249.                 {  
  250.                     strWhere = AddWithAnd(strWhere, dt.Columns[iPK].ColumnName + "=?");  
  251.                 }  
  252.                 strWhere = " Where " + strWhere;  
  253.                 for (int iCol = 0; iCol < dt.Columns.Count; iCol++)  
  254.                 {  
  255.                     strInsert = AddWithComma(strInsert, dt.Columns[iCol].ColumnName);  
  256.                     strInsertPar = AddWithComma(strInsertPar, "?");  
  257.                     strUpdate = AddWithComma(strUpdate, dt.Columns[iCol].ColumnName) + "=?";  
  258.                 }  
  259.                 string strTable = "[" + this.SheetName + "$" + this.SheetRange + "]";  
  260.                 strInsert = "INSERT INTO " + strTable + "(" + strInsert + ") Values (" + strInsertPar + ")";  
  261.                 strUpdate = "Update " + strTable + " Set " + strUpdate + strWhere;  
  262.                 oleda.InsertCommand = new OleDbCommand(strInsert, _oleConn);  
  263.                 oleda.UpdateCommand = new OleDbCommand(strUpdate, _oleConn);  
  264.                 OleDbParameter oleParIns = null;  
  265.                 OleDbParameter oleParUpd = null;  
  266.                 for (int iCol = 0; iCol < dt.Columns.Count; iCol++)  
  267.                 {  
  268.                     oleParIns = new OleDbParameter("?", dt.Columns[iCol].DataType.ToString());  
  269.                     oleParUpd = new OleDbParameter("?", dt.Columns[iCol].DataType.ToString());  
  270.                     oleParIns.SourceColumn = dt.Columns[iCol].ColumnName;  
  271.                     oleParUpd.SourceColumn = dt.Columns[iCol].ColumnName;  
  272.                     oleda.InsertCommand.Parameters.Add(oleParIns);  
  273.                     oleda.UpdateCommand.Parameters.Add(oleParUpd);  
  274.                     oleParIns = null;  
  275.                     oleParUpd = null;  
  276.                 }  
  277.                 for (int iPK = 0; iPK < PKCols.Length; iPK++)  
  278.                 {  
  279.                     oleParUpd = new OleDbParameter("?", dt.Columns[iPK].DataType.ToString());  
  280.                     oleParUpd.SourceColumn = dt.Columns[iPK].ColumnName;  
  281.                     oleParUpd.SourceVersion = DataRowVersion.Original;  
  282.                     oleda.UpdateCommand.Parameters.Add(oleParUpd);  
  283.                 }  
  284.                 return oleda;  
  285.             }  
  286.             catch (Exception ex)  
  287.             {  
  288.                 throw ex;  
  289.             }  
  290.         }  
  291.         command Singe Value Update#region command Singe Value Update  
  292.         private bool SetSheetQuerySingelValUpdate(string strVal)  
  293.         {  
  294.             try  
  295.             {  
  296.                 if (_oleConn == null)  
  297.                 {  
  298.                     throw new Exception("Connection is unassigned or closed.");  
  299.                 }  
  300.                 if (_strSheetName.Length == 0)  
  301.                     throw new Exception("Sheetname was not assigned.");  
  302.                 _oleCmdUpdate = new OleDbCommand(  
  303.                     @" Update ["  
  304.                     + _strSheetName  
  305.                     + "$" + _strSheetRange  
  306.                     + "] set F1=" + strVal, _oleConn);  
  307.                 return true;  
  308.             }  
  309.             catch (Exception ex)  
  310.             {  
  311.                 throw ex;  
  312.             }  
  313.         }  
  314.         #endregion  
  315.         public void SetPrimaryKey(int intCol)  
  316.         {  
  317.             _PKCol = new int[1] { intCol };  
  318.         }  
  319.         public DataTable GetTable()  
  320.         {  
  321.             return GetTable("ExcelTable");  
  322.         }  
  323.         private void SetPrimaryKey(DataTable dt)  
  324.         {  
  325.             try  
  326.             {  
  327.                 if (PKCols != null)  
  328.                 {  
  329.                     //set the primary key  
  330.                     if (PKCols.Length > 0)  
  331.                     {  
  332.                         DataColumn[] dc;  
  333.                         dc = new DataColumn[PKCols.Length];  
  334.                         for (int i = 0; i < PKCols.Length; i++)  
  335.                         {  
  336.                             dc[i] = dt.Columns[PKCols[i]];  
  337.                         }  
  338.                         dt.PrimaryKey = dc;  
  339.                     }  
  340.                 }  
  341.             }  
  342.             catch (Exception ex)  
  343.             {  
  344.                 throw ex;  
  345.             }  
  346.         }  
  347.         public DataTable GetTable(string strTableName)  
  348.         {  
  349.             try  
  350.             {  
  351.                 //Open and query  
  352.                if (_oleConn == null)  Open();  
  353.                 if (_oleConn.State != ConnectionState.Open)  
  354.                     throw new Exception("Connection cannot open error.");  
  355.                 if (SetSheetQuerySelect() == falsereturn null;  
  356.                 //Fill table  
  357.                 OleDbDataAdapter oleAdapter = new OleDbDataAdapter();  
  358.                 oleAdapter.SelectCommand = _oleCmdSelect;  
  359.                 DataTable dt = new DataTable(strTableName);  
  360.                 oleAdapter.FillSchema(dt, SchemaType.Source);  
  361.                 oleAdapter.Fill(dt);  
  362.                 if (this.Headers == false)  
  363.                 {  
  364.                     if (_strSheetRange.IndexOf(":") > 0)  
  365.                     {  
  366.                         string FirstCol = _strSheetRange.Substring(0, _strSheetRange.IndexOf(":") - 1);  
  367.                         

猜你喜欢

转载自blog.csdn.net/gfuugfdkkn/article/details/84101867