在項目中使用到遇到了需要將excel文件導入到數(shù)據(jù)庫中斟薇,在此做個總結記錄设江,防止后面人踩坑袋励。
開發(fā)環(huán)境:VS2008+Win10
第一種方式:Office.Interop.Excel方式 數(shù)據(jù)量大時有點慢
public static DataTable getExcelDataKHFY(string fileName, DataTable dt)
{
string[] names = GetExcelTableName(fileName);
int ysCount = 0;//獲取頁數(shù)
string exname = "";
if (names.Length > 1)
{
Yx_Module.winChangeExcel win = new THKClient.Yx_Module.winChangeExcel(names);
win.ShowDialog();
if (win.IsReturn)
{
ysCount = int.Parse(win.Excelid) + 1;//頁碼
exname = win.ExName;//選擇的頁名
}
}
DataTable result = dt;
Microsoft.Office.Interop.Excel.Application xlApp = null;
Microsoft.Office.Interop.Excel.Workbook xlWorkbook = null;
try
{
xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null) return null;
xlApp.Visible = false;
xlWorkbook = xlApp.Workbooks.Open(fileName, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
Dictionary<int, Microsoft.Office.Interop.Excel.Range> rowrange = new Dictionary<int, Microsoft.Office.Interop.Excel.Range>();
if (ysCount != 0)
{
try
{
//動態(tài)頁插入數(shù)據(jù)
int i = ysCount;
// Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkbook.Sheets[i];//根據(jù)頁碼
Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkbook.Sheets[exname];//根據(jù)頁名獲取
string str = sheet.Name;
for (int rowIndex = 2; rowIndex < sheet.Cells.Rows.Count - 1; rowIndex++)
{
rowrange.Clear();
object[] parm = new object[result.Columns.Count];
for (int j = 0; j < result.Columns.Count; j++)
{
rowrange[j] = (Microsoft.Office.Interop.Excel.Range)(sheet.Cells[rowIndex, j + 1]);
parm[j] = rowrange[j].Value2 == null ? "" : rowrange[j].Value2.ToString();
}
rowrange.Clear();
if (parm[0].ToString().Trim().Length == 0)
{
break;
}
result.Rows.Add(parm);
}
}
catch (Exception ee)
{
throw;
}
}
else
{
for (int i = 1; i < xlWorkbook.Sheets.Count + 1; i++)
{
Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkbook.Sheets[i];
string str = sheet.Name;
for (int rowIndex = 2; rowIndex < sheet.Cells.Rows.Count - 1; rowIndex++)
{
rowrange.Clear();
object[] parm = new object[result.Columns.Count];
for (int j = 0; j < result.Columns.Count; j++)
{
rowrange[j] = (Microsoft.Office.Interop.Excel.Range)(sheet.Cells[rowIndex, j + 1]);
parm[j] = rowrange[j].Value2 == null ? "" : rowrange[j].Value2.ToString();
}
rowrange.Clear();
if (parm[0].ToString().Trim().Length == 0)
{
break;
}
result.Rows.Add(parm);
}
}
}
xlWorkbook.Close(Type.Missing, Type.Missing, Type.Missing);
xlApp.Quit();
}
finally
{
Marshal.ReleaseComObject(xlWorkbook);
Marshal.ReleaseComObject(xlApp);
xlApp = null;
List<Process> excelProcesses = GetExcelProcesses();
if (excelProcesses.Count > 0)
{
KillTheExcel();//殺死進程
}
}
return result;
}
第二種方式:NPOI方式 此種方式最優(yōu)
/// <summary>讀取excel
/// 默認第一行為表頭
/// </summary>
/// <param name="strFileName">excel文檔路徑</param>
/// <returns></returns>
public static DataTable Import(string strFileName)
{
DataTable dt = new DataTable();
HSSFWorkbook hssfworkbook;
using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
{
hssfworkbook = new HSSFWorkbook(file);
}
HSSFSheet sheet = hssfworkbook.GetSheetAt(0);
System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
HSSFRow headerRow = sheet.GetRow(0);
int cellCount = headerRow.LastCellNum;
for (int j = 0; j < cellCount; j++)
{
HSSFCell cell = headerRow.GetCell(j);
dt.Columns.Add(cell.ToString());
}
for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
{
HSSFRow row = sheet.GetRow(i);
DataRow dataRow = dt.NewRow();
for (int j = row.FirstCellNum; j < cellCount; j++)
{
if (row.GetCell(j) != null)
dataRow[j] = row.GetCell(j).ToString();
}
dt.Rows.Add(dataRow);
}
return dt;
}
第三種方式:OLEDB方式 需要將程序設置為X86運行
public static DataTable ExcelToDataTable(string filePath)
{
string connStr = "";
string fileType = System.IO.Path.GetExtension(filePath);
if (string.IsNullOrEmpty(fileType)) return null;
if (fileType == ".xls")
connStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filePath + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
else
connStr = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + filePath + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
string sql_F = "Select * FROM [{0}]";
DataSet ds = new DataSet();
//using (OleDbConnection myConn = new OleDbConnection(connStr))
//{
// using (OleDbDataAdapter myCommand = new OleDbDataAdapter(sql_F, myConn))
// {
// myConn.Open();
// myCommand.Fill(ds);
// }
//}
//if (ds == null || ds.Tables.Count <= 0) return null;
//return ds.Tables[0];
OleDbConnection conn = null;
OleDbDataAdapter da = null;
DataTable dtSheetName = null;
try
{
// 初始化連接角虫,并打開
conn = new OleDbConnection(connStr);
conn.Open();
// 獲取數(shù)據(jù)源的表定義元數(shù)據(jù)
string SheetName = "";
dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
// 初始化適配器
da = new OleDbDataAdapter();
for (int i = 0; i < dtSheetName.Rows.Count; i++)
{
SheetName = (string)dtSheetName.Rows[i]["TABLE_NAME"];
if (SheetName.Contains("$") && !SheetName.Replace("'", "").EndsWith("$"))
{
continue;
}
da.SelectCommand = new OleDbCommand(String.Format(sql_F, SheetName), conn);
DataSet dsItem = new DataSet();
da.Fill(dsItem);
ds.Tables.Add(dsItem.Tables[0].Copy());
}
}
catch (Exception ex)
{
}
finally
{
// 關閉連接
if (conn.State == ConnectionState.Open)
{
conn.Close();
da.Dispose();
conn.Dispose();
}
}
return ds.Tables[0];
}