日期:2014-05-18 浏览次数:20969 次
using MSExcel=Microsoft.Office.Interop.Excel; private void InsertXlsToDataBase()//将Excel文件中的数据导入数据库中 { int i = 2; string cName = "", cId = ""; MSExcel.Application XlsA = new MSExcel.Application(); if (XlsA == null) { MessageBox.Show("无法创建Excel对象,情检查Excel是否可用或者是否安装好Excel!", "系统提示"); return; } MSExcel.Workbooks XlsW = XlsA.Workbooks; MSExcel.Workbook XlsW1 = XlsW.Add(cFilePath); MSExcel.Sheets XlsS = XlsW1.Sheets; MSExcel.Worksheet XlsS1 = (MSExcel.Worksheet)XlsS[1]; try { while (XlsA.get_Range(XlsA.Cells[i,1],XlsA.Cells[i,1]).Value2.ToString().Trim() != "") { cName = XlsA.get_Range(XlsA.Cells[i, 1], XlsA.Cells[i, 1]).Value2.ToString(); cId = XlsA.get_Range(XlsA.Cells[i, 2], XlsA.Cells[i, 2]).Value2.ToString(); string SqlStr = "insert into Table1(cName,cId) values('" + cName + "','" + cId + "')"; CDataBase.UpdateDB(SqlStr); i++; } } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { XlsW.Close(); XlsA.Quit(); } }