UtilExcel.cs 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using System;
  2. using System.Reflection;
  3. using System.Collections;
  4. using System.Resources;
  5. using System.Windows.Forms;
  6. using System.Data;
  7. using Excel = Microsoft.Office.Interop.Excel;
  8. using System.Collections.Generic;
  9. using System.Data.OleDb;
  10. namespace Core.StlMes.Client.Sale.Util
  11. {
  12. public class UtilExcel
  13. {
  14. public static string GetExcelFileName()
  15. {
  16. OpenFileDialog openFileDialog = new OpenFileDialog();
  17. openFileDialog.InitialDirectory = @"C:\桌面\"; //指定打开文件默认路径
  18. openFileDialog.Filter = "Excel文件(*.xlsx;*.xls)|*.xlsx;*.xls"; //指定打开默认选择文件类型名
  19. openFileDialog.RestoreDirectory = true;
  20. openFileDialog.FilterIndex = 1;
  21. if (openFileDialog.ShowDialog() == DialogResult.OK)
  22. {
  23. return openFileDialog.FileName;
  24. }
  25. return "";
  26. }
  27. public static DataSet ToDataSet(string filePath)
  28. {
  29. string connStr = "";
  30. string fileType = System.IO.Path.GetExtension(filePath);
  31. if (string.IsNullOrEmpty(fileType)) return null;
  32. if (fileType == ".xls")
  33. connStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filePath + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
  34. else
  35. connStr = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + filePath + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
  36. string sql_F = "Select * FROM [{0}]";
  37. OleDbConnection conn = null;
  38. OleDbDataAdapter da = null;
  39. DataTable dtSheetName = null;
  40. DataSet ds = new DataSet();
  41. try
  42. {
  43. // 初始化连接,并打开
  44. conn = new OleDbConnection(connStr);
  45. conn.Open();
  46. // 获取数据源的表定义元数据                       
  47. string SheetName = "";
  48. dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
  49. // 初始化适配器
  50. da = new OleDbDataAdapter();
  51. for (int i = 0; i < dtSheetName.Rows.Count; i++)
  52. {
  53. SheetName = (string)dtSheetName.Rows[i]["TABLE_NAME"];
  54. if (SheetName.Contains("$") && !SheetName.Replace("'", "").EndsWith("$"))
  55. {
  56. continue;
  57. }
  58. da.SelectCommand = new OleDbCommand(String.Format(sql_F, SheetName), conn);
  59. DataSet dsItem = new DataSet();
  60. da.Fill(dsItem, SheetName);
  61. // Only Get the first sheet data
  62. ds.Tables.Add(dsItem.Tables[0].Copy());
  63. break;
  64. }
  65. }
  66. catch (Exception ex)
  67. {
  68. }
  69. finally
  70. {
  71. // 关闭连接
  72. if (conn.State == ConnectionState.Open)
  73. {
  74. conn.Close();
  75. da.Dispose();
  76. conn.Dispose();
  77. }
  78. }
  79. return ds;
  80. }
  81. }
  82. }