思路很简单,就是先依次获取Excel中表的表名,然后再将Excel表的数据导入到内存以DataTable格式存在,最后再把dataTable数据导入到Mdb数据库文件中。最后实现的功能可以使Excel多表进行导入,如果Mdb数据库文件中已有新建的表, *** 作是先删除数据库中的已存在表,再重新创建表,导数据。
源码:
using Systemusing System.Collections.Genericusing System.ComponentModelusing System.Datausing System.Drawingusing System.Linqusing System.Textusing System.Threading.Tasksusing System.Windows.Formsusing System.Data.OleDb
namespace TestK
{
public partial class Form1 : Form {
public Form1()
{
InitializeComponent()
}
public int tableNameNum = 0 //记录Excel中所有表的数量 public OleDbConnection connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0Data Source=C:\\Users\\CES\\Desktop\\CES.mdb")
//建立与数据库文件CES.mdb的连接
//打开以.xls或者.xlsx结尾的文件 private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog() //创建窗体 dlg.Filter = "Excel文件 (*.xls*.xlsx)|*.xls*.xlsx" //浏览过滤出以.xls或者.xlsx结尾的文件 if(dlg.ShowDialog() == DialogResult.OK)
{
string filePath = dlg.FileName //获取打开文件的路径 this.textBox1.Text = filePath
}
}
//获取Excel中所有表的表名 public string[] GetTableName(string excelFilename)
{
//建立与指定Excel文件的连接 string connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0Data Source={0}Jet OLEDB:Engine Type=35Extended Properties=Excel 8.0Persist Security Info=False", excelFilename)
string[] tableName = new string[20] //存储Excel中所有表的表名 string temp //中间变量
using (System.Data.OleDb.OleDbConnection connection = new System.Data.OleDb.OleDbConnection(connectionString))
{
connection.Open()
//获取数据库架构信息,包括列、主键、表等信息 DataTable table = connection.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null)
for (int i = 0 i < table.Rows.Counti++ )
{
temp = table.Rows[i]["Table_Name"].ToString() //获取Excel中的表名 tableName[i] = temp.Replace("$", "") //因为获取的表名最后会有$符号,所以要替换 }
tableNameNum = table.Rows.Count
connection.Close()
}
return tableName
}
//获取Excel中每张表的数据,以datatable类型返回 public DataTable GetExcelTable(string excelFilename,string tableName)
{
//建立与指定Excel文件的连接 string connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0Data Source={0}Jet OLEDB:Engine Type=35Extended Properties=Excel 8.0Persist Security Info=False", excelFilename)
DataSet ds = new DataSet() //数据集 //using中声明的对象connection,在using语句块结束后会自动释放 using (System.Data.OleDb.OleDbConnection connection = new System.Data.OleDb.OleDbConnection(connectionString))
{
connection.Open()
//获取数据库架构信息,包括列、主键、表等信息 DataTable table = connection.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null)
string strExcel = "select * from " + "[" + tableName + "$]"
//打开数据链接,得到一个数据集 OleDbDataAdapter adapter = new OleDbDataAdapter(strExcel, connectionString)
//在数据集中查询表名为tableName的表,然后把其数据在装入数据集ds中 adapter.Fill(ds, tableName)
connection.Close()
}
return ds.Tables[tableName]//以datatable类型返回数据集ds中表名为tableName的表 }
//判断在数据库中,指定表名的表是否存在 public bool TableExists(string table)
{
bool rythm
connection.Open()
//读取表名为table的表的行数信息 rythm = connection.GetSchema("Tables", new string[4] { null, null, table, "TABLE" }).Rows.Count > 0
connection.Close()
return rythm
}
//如果在建表之前,数据库已经存在该表,那么首先要先删除此表 public void DeleteTable(string tableName)
{
string sql = "drop table "+tableName+""
connection.Open()
OleDbCommand cmd = new OleDbCommand(sql, connection)
cmd.ExecuteNonQuery()
connection.Close()
}
//中间类型为dataTable的表数据转换到数据库mdb文件中 public bool dataTableToMdb(string excelPath,string tableName)
{
//获取Excel中表的数据 DataTable dt = GetExcelTable(excelPath,tableName)
//表中数据大于等于两行,数据转入格式才是正确的 if (dt.Rows.Count >= 2)
{
string[] cloumnName = new string[50]
//获取Excel中表的所有列名 for (int i = 0 i < dt.Columns.Count i++)
{
cloumnName[i] = dt.Rows[0][i].ToString()
}
//在mdb数据库文件中创建表 string sql = "create table " + tableName + " (" + cloumnName[0] + " varchar null)"
connection.Open()
OleDbCommand cmd = new OleDbCommand(sql, connection)
cmd.ExecuteNonQuery()
//在mdb数据库文件中,给已创建好的表添加好所有列 for (int i = 1 i < dt.Columns.Count i++)
{
sql = "alter table " + tableName + " add " + cloumnName[i] + " varchar null"
cmd = new OleDbCommand(sql, connection)
cmd.ExecuteNonQuery()
}
//在mdb数据库文件中,给已创建好的表加入数据 for (int t = 1 t < dt.Rows.Count t++)
{
sql = "insert into " + tableName + " values('"
for (int k = 0 k < dt.Columns.Count k++)
{
if (k != dt.Columns.Count - 1)
{
sql = sql + dt.Rows[t][k].ToString() + "','"
}
else {
sql = sql + dt.Rows[t][k].ToString() + "')"
}
}
cmd = new OleDbCommand(sql, connection)
cmd.ExecuteNonQuery()
}
connection.Close()
return true
}
else {
MessageBox.Show("Excel中"+ tableName +"表的原始数据格式不正确!")
}
return false
}
private void button2_Click(object sender, EventArgs e)
{
int flag = 1 //判断由Excel表导入到Mdb是否成功的标记变量
导入excel一般分为两步,先上传再解析插入数据库。。。核心代码就是下面这两个方法,前几天刚写的例子://上传:
public String doUpload() throws Exception{
System.out.println(upload)
System.out.println(uploadContentType)
System.out.println(uploadFileName)
//根据逻辑路径获取实际上传到服务器的路径(物理路径)
// D:\\apache-tomcat-6.0.30\\apache-tomcat-6.0.30\\webapps\\
//Struts2_chapter04_02fileUpload\\upload
String savePath =
ServletActionContext.
getServletContext().
getRealPath("/upload/"+this.uploadFileName)
FileInputStream fis =
new FileInputStream(upload)
FileOutputStream fos =
new FileOutputStream(savePath)
IOUtils.copy(fis, fos)
fos.flush()
fos.close()
fis.close()
addOrder(this.uploadFileName)
return SUCCESS
}
//解析并插入数据库
public void addOrder(String uploadFileFileName) throws Exception{
String directory = "/upload"
String targetDirectory = ServletActionContext.getServletContext().getRealPath(directory)
File target = new File(targetDirectory,uploadFileFileName)
boList = new ArrayList<BC_ORDERDETAILBean>()
try{
FileInputStream fi = new FileInputStream(target)
Workbook wb = new HSSFWorkbook(fi)
Sheet sheet = wb.getSheetAt(0)
int rowNum = sheet.getLastRowNum()+1
for(int i=1i<rowNumi++){
BC_ORDERDETAILBean bo = new BC_ORDERDETAILBean()
Row row = sheet.getRow(i)
int cellNum = row.getLastCellNum()
for(int j=0j<cellNumj++){
Cell cell = row.getCell(j)
String cellValue = null
switch(cell.getCellType()){ //判断excel单元格内容的格式,并对其进行转换,以便插入数据库
case 0 : cellValue = String.valueOf((int)cell.getNumericCellValue())break
case 1 : cellValue = cell.getStringCellValue()break
case 2 : cellValue = String.valueOf(cell.getDateCellValue())break
case 3 : cellValue = ""break
case 4 : cellValue = String.valueOf(cell.getBooleanCellValue())break
case 5 : cellValue = String.valueOf(cell.getErrorCellValue())break
}
switch(j){//通过列数来判断对应插如的字段
case 0 : bo.setB2ccertno(cellValue)break
case 1 : bo.setSeqno(cellValue)break
case 2 : bo.setOrderno(cellValue)break
case 3 : bo.setProductname(cellValue)break
case 4 : bo.setTerm(cellValue)break
case 5 : bo.setQuantity(cellValue)break
case 6 : bo.setSubtotal(cellValue)break
case 7 : bo.setProductcode(cellValue)break
case 8 : bo.setNote(cellValue)break
case 9 : bo.setConsignee(cellValue)break
case 10 : bo.setConsigneeaddress(cellValue)break
case 11 : bo.setConsigneephone(cellValue)break
}
}
boList.add(bo)
}
IOrderDao iod = new OrderDao()
iod.addBOtoDB(boList)
}catch(IOException e){
e.printStackTrace()
}
}
假设你的EXCEL都已经是标准格式的文件了,那么你可以使用以下代码进行 *** 作:变量定义及ADO对象创建
....
strConn
=
"Provider=Microsoft.Jet.OLEDB.4.0"
&
_
"Data
Source="
&
strExcelFile
&
_
"Extended
Properties=Excel
8.0"
strToDBConn
=
"odbcDriver={SQL
Server}Server=IP地址Database=数据库名UID=登录用户PWD=密码"
'//
以记录集的形式打开
Excel
文件
adoConn.Open
strConn
'//
将数据插入到指定的表中
strSQL
=
"INSERT
INTO
["
&
strToDBConn
&
"].SQL数据库中的表名
SELECT
EXCEL中的字段名(第一行)
FROM
EXECL工作表名"
adoConn.Execute
strSQL,
,
adExecuteNoRecords
'//
这里有可能会产生一个错误,“系统不支持所选择的排序。(-2147467259)”
'//
但实际上已经有执行成功了,所以忽略此错误
If
Err.Number
=
-2147467259
Then
Err.Clear
End
If
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)