2、如果出错(比如数据库中有重复信息或者唯一约束等),怎么显示或者生成错误信息到一个文件里
谢谢~
26 个解决方案
#1
帮你顶,没有用过
#2
我只知道大概是...
先将Excel做为数据源加载到前台:
Dim str As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & Me.txt文件名.Text & ";" & _
"Extended Properties=""Excel 8.0;HDR=YES"""
Dim dcolink As New System.Data.OleDb.OleDbConnection(str)
Dim da As New System.Data.OleDb.OleDbDataAdapter("Select * From [Sheet1$]", dcolink)
Dim ds As New Data.DataSet()
da.Fill(ds, [Sheet1$]) '从Excel中导入的原始数据
然后用循环整个数据集的行,条件(重复信息或者唯一约束)成立的就Update...Insert...到数据库。
期待高手解答...
先将Excel做为数据源加载到前台:
Dim str As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & Me.txt文件名.Text & ";" & _
"Extended Properties=""Excel 8.0;HDR=YES"""
Dim dcolink As New System.Data.OleDb.OleDbConnection(str)
Dim da As New System.Data.OleDb.OleDbDataAdapter("Select * From [Sheet1$]", dcolink)
Dim ds As New Data.DataSet()
da.Fill(ds, [Sheet1$]) '从Excel中导入的原始数据
然后用循环整个数据集的行,条件(重复信息或者唯一约束)成立的就Update...Insert...到数据库。
期待高手解答...
#3
up,学习
#4
1。将EXCEL中数据先存进DATATALE,在将数据提取出来存进数据库就OK了!
2。在过程中采取事务捕捉异常!
2。在过程中采取事务捕捉异常!
#5
五楼能说具体点儿么?最好有点代码~
#6
Dim myConn As New OleDbConnection
Dim myAdaptor As New OleDbDataAdapter
Dim dt As New DataTable
Dim ds As New DataSet
Dim MyRow As DataRow
Dim strTemp As String
Dim i As Integer
Dim my_TableType As String '传入的文件类型
Dim strConn As String '连接字符
Dim strSql As String '查询字符
Dim strSplit As String '传入的文件名
Dim reader As StreamReader '定义IO流
Dim fs As FileStream '定义文件输出流
OpenFileDialog1.AddExtension = True
OpenFileDialog1.CheckFileExists = True
OpenFileDialog1.Title = "请选择要导入的文件"
OpenFileDialog1.Filter = "*.Excel文件|*.xls"
OpenFileDialog1.ShowDialog()
strSplit = OpenFileDialog1.FileName
my_TableType = Microsoft.VisualBasic.Right(strSplit, 4)
Dim ArrCSC As Array
Dim intCSC As Integer
Dim strCSC As String
If my_TableType = ".xls" Or my_TableType = ".XLS" Then
If txtCSCID.Text = "" Then
ArrCSC = Split(strSplit, "\")
intCSC = ArrCSC.Length
strCSC = ArrCSC(intCSC - 1)
strCSC = Microsoft.VisualBasic.Left(strCSC, strCSC.Length - 4)
cmbCSCName.Text = strCSC
Dim Showup As New Client
Showup.CSC_Name = Trim(cmbCSCName.Text) '获得客户名称
Showup.getCSCDetailByName(Showup.CSC_Name) '获取客户的详细情况
txtCSCID.Text = Showup.CSC_ID
txtAddress.Text = Showup.Address
txtTel.Text = Showup.Tel
txtLinkMan.Text = Showup.LinkMan
txtZip.Text = Showup.Zip
txtFax.Text = Showup.Fax
cmbCSCName.Enabled = False
cmbCSCName.BackColor = New Color
txtEMail.Text = Showup.Email
'Showup.getCS(Showup.CSC_Name)
'txtCSName.Text = Showup.CS
'txtCSID.Text = Showup.CSID
End If
'导入excel文件
Dim MyFalut As New Fault
Dim MyProduct As New Product
Dim MyMaterial As New Material
Dim MyLLBLLX As New LLBLLX
Dim MyUnitsType As New HandGet
Try
GetOperateLog(9522)
strConn = "provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;data source=" + strSplit + ""
strSql = "Select * From[sheet1$]"
myConn = New OleDbConnection(strConn)
myConn.Open()
myAdaptor = New OleDbDataAdapter(strSql, myConn)
myAdaptor.Fill(ds, "ExcelData")
dt = ds.Tables(0)
For i = 0 To dt.Rows.Count - 1
MyRow = MyDataTable.NewRow
MyRow(2) = dt.Rows(i).Item("物料类型")
If IsDBNull(MyRow(2)) = False Then
MyUnitsType.GetUnitsType_ID(Trim(dt.Rows(i).Item("物料类型")))
MyRow(1) = MyUnitsType.UnitType_Id
Else
MyRow(1) = DBNull.Value
End If
MyRow(3) = dt.Rows(i).Item("条形码")
MyRow(4) = dt.Rows(i).Item("物料名称")
If IsDBNull(MyRow(4)) = False Then
MyMaterial.GetUnits_ID(Trim(dt.Rows(i).Item("物料名称"))) '传递物料名称
MyRow(5) = MyMaterial.Units_ID
Else
MyRow(5) = DBNull.Value
End If
MyRow(7) = dt.Rows(i).Item("小灵通机型")
If IsDBNull(dt.Rows(i).Item("小灵通机型")) = False Then
MyProduct.GetProductID(Trim(dt.Rows(i).Item("小灵通机型"))) '传递机型名称
MyRow(6) = MyProduct.Product_ID
Else
MyRow(6) = DBNull.Value
MyRow(7) = ""
End If
MyRow(8) = dt.Rows(i).Item("小灵通号码")
MyRow(9) = dt.Rows(i).Item("购买时间")
MyRow(10) = dt.Rows(i).Item("投诉时间")
MyRow(11) = dt.Rows(i).Item("用户姓名")
MyRow(12) = dt.Rows(i).Item("联系电话")
MyRow(13) = dt.Rows(i).Item("送修人")
MyRow(14) = dt.Rows(i).Item("送修人电话")
MyRow(16) = dt.Rows(i).Item("故障类型")
If IsDBNull(MyRow(16)) = False Then
MyFalut.GetFaultName(Trim(dt.Rows(i).Item("故障类型"))) '传递故障名称
MyRow(15) = MyFalut.Fault_ID
Else
MyRow(15) = DBNull.Value
End If
MyRow(17) = dt.Rows(i).Item("故障描述")
MyRow(18) = dt.Rows(i).Item("是否保修")
MyRow(19) = dt.Rows(i).Item("是否来料不良")
MyRow(21) = dt.Rows(i).Item("来料不良类型")
If IsDBNull(MyRow(21)) = False Then
MyLLBLLX.GetLLBLLXID(Trim(dt.Rows(i).Item("来料不良类型"))) '传递来料不良名称
MyRow(20) = MyLLBLLX.LLBLLX_ID
Else
MyRow(20) = DBNull.Value
End If
MyRow(22) = dt.Rows(i).Item("是否是SP")
MyRow(23) = dt.Rows(i).Item("SP名称")
MyRow(24) = dt.Rows(i).Item("是否是大客户")
MyDataTable.Rows.Add(MyRow)
Next
Catch ex As Exception
Dim exm As String = ex.Message
GetErrLog(ex)
MessageBox.Show("系统执行时发生以下错误:" + vbCrLf.ToString + "错误源:" + ex.Source.ToString.ToString + vbCrLf.ToString + "错误信息:" + ex.Message.ToString + vbCrLf.ToString + vbCrLf.ToString + "请记录错误信息,并与管理员联系。", "PurpleStar", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)
Finally
myConn.Close()
myConn = Nothing
End Try
Else
Exit Sub
End If
这是将数据从EXCEL读出显示在DATAGRID里的,剩下的部分我手头没有源码,不好意思!
Dim myAdaptor As New OleDbDataAdapter
Dim dt As New DataTable
Dim ds As New DataSet
Dim MyRow As DataRow
Dim strTemp As String
Dim i As Integer
Dim my_TableType As String '传入的文件类型
Dim strConn As String '连接字符
Dim strSql As String '查询字符
Dim strSplit As String '传入的文件名
Dim reader As StreamReader '定义IO流
Dim fs As FileStream '定义文件输出流
OpenFileDialog1.AddExtension = True
OpenFileDialog1.CheckFileExists = True
OpenFileDialog1.Title = "请选择要导入的文件"
OpenFileDialog1.Filter = "*.Excel文件|*.xls"
OpenFileDialog1.ShowDialog()
strSplit = OpenFileDialog1.FileName
my_TableType = Microsoft.VisualBasic.Right(strSplit, 4)
Dim ArrCSC As Array
Dim intCSC As Integer
Dim strCSC As String
If my_TableType = ".xls" Or my_TableType = ".XLS" Then
If txtCSCID.Text = "" Then
ArrCSC = Split(strSplit, "\")
intCSC = ArrCSC.Length
strCSC = ArrCSC(intCSC - 1)
strCSC = Microsoft.VisualBasic.Left(strCSC, strCSC.Length - 4)
cmbCSCName.Text = strCSC
Dim Showup As New Client
Showup.CSC_Name = Trim(cmbCSCName.Text) '获得客户名称
Showup.getCSCDetailByName(Showup.CSC_Name) '获取客户的详细情况
txtCSCID.Text = Showup.CSC_ID
txtAddress.Text = Showup.Address
txtTel.Text = Showup.Tel
txtLinkMan.Text = Showup.LinkMan
txtZip.Text = Showup.Zip
txtFax.Text = Showup.Fax
cmbCSCName.Enabled = False
cmbCSCName.BackColor = New Color
txtEMail.Text = Showup.Email
'Showup.getCS(Showup.CSC_Name)
'txtCSName.Text = Showup.CS
'txtCSID.Text = Showup.CSID
End If
'导入excel文件
Dim MyFalut As New Fault
Dim MyProduct As New Product
Dim MyMaterial As New Material
Dim MyLLBLLX As New LLBLLX
Dim MyUnitsType As New HandGet
Try
GetOperateLog(9522)
strConn = "provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;data source=" + strSplit + ""
strSql = "Select * From[sheet1$]"
myConn = New OleDbConnection(strConn)
myConn.Open()
myAdaptor = New OleDbDataAdapter(strSql, myConn)
myAdaptor.Fill(ds, "ExcelData")
dt = ds.Tables(0)
For i = 0 To dt.Rows.Count - 1
MyRow = MyDataTable.NewRow
MyRow(2) = dt.Rows(i).Item("物料类型")
If IsDBNull(MyRow(2)) = False Then
MyUnitsType.GetUnitsType_ID(Trim(dt.Rows(i).Item("物料类型")))
MyRow(1) = MyUnitsType.UnitType_Id
Else
MyRow(1) = DBNull.Value
End If
MyRow(3) = dt.Rows(i).Item("条形码")
MyRow(4) = dt.Rows(i).Item("物料名称")
If IsDBNull(MyRow(4)) = False Then
MyMaterial.GetUnits_ID(Trim(dt.Rows(i).Item("物料名称"))) '传递物料名称
MyRow(5) = MyMaterial.Units_ID
Else
MyRow(5) = DBNull.Value
End If
MyRow(7) = dt.Rows(i).Item("小灵通机型")
If IsDBNull(dt.Rows(i).Item("小灵通机型")) = False Then
MyProduct.GetProductID(Trim(dt.Rows(i).Item("小灵通机型"))) '传递机型名称
MyRow(6) = MyProduct.Product_ID
Else
MyRow(6) = DBNull.Value
MyRow(7) = ""
End If
MyRow(8) = dt.Rows(i).Item("小灵通号码")
MyRow(9) = dt.Rows(i).Item("购买时间")
MyRow(10) = dt.Rows(i).Item("投诉时间")
MyRow(11) = dt.Rows(i).Item("用户姓名")
MyRow(12) = dt.Rows(i).Item("联系电话")
MyRow(13) = dt.Rows(i).Item("送修人")
MyRow(14) = dt.Rows(i).Item("送修人电话")
MyRow(16) = dt.Rows(i).Item("故障类型")
If IsDBNull(MyRow(16)) = False Then
MyFalut.GetFaultName(Trim(dt.Rows(i).Item("故障类型"))) '传递故障名称
MyRow(15) = MyFalut.Fault_ID
Else
MyRow(15) = DBNull.Value
End If
MyRow(17) = dt.Rows(i).Item("故障描述")
MyRow(18) = dt.Rows(i).Item("是否保修")
MyRow(19) = dt.Rows(i).Item("是否来料不良")
MyRow(21) = dt.Rows(i).Item("来料不良类型")
If IsDBNull(MyRow(21)) = False Then
MyLLBLLX.GetLLBLLXID(Trim(dt.Rows(i).Item("来料不良类型"))) '传递来料不良名称
MyRow(20) = MyLLBLLX.LLBLLX_ID
Else
MyRow(20) = DBNull.Value
End If
MyRow(22) = dt.Rows(i).Item("是否是SP")
MyRow(23) = dt.Rows(i).Item("SP名称")
MyRow(24) = dt.Rows(i).Item("是否是大客户")
MyDataTable.Rows.Add(MyRow)
Next
Catch ex As Exception
Dim exm As String = ex.Message
GetErrLog(ex)
MessageBox.Show("系统执行时发生以下错误:" + vbCrLf.ToString + "错误源:" + ex.Source.ToString.ToString + vbCrLf.ToString + "错误信息:" + ex.Message.ToString + vbCrLf.ToString + vbCrLf.ToString + "请记录错误信息,并与管理员联系。", "PurpleStar", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)
Finally
myConn.Close()
myConn = Nothing
End Try
Else
Exit Sub
End If
这是将数据从EXCEL读出显示在DATAGRID里的,剩下的部分我手头没有源码,不好意思!
#7
其实上面的代码已经实现了将EXCEL数据存储在DATATABLE里的功能,你现在只要对DATATABLE依次循环取值,在逐条存进数据库OK了,最好将从DATATABLE取出数据存入数据库的过程加在TRY和CATCH之间,这样便于捕捉异常。还有在存储数据到数据库时要加事务,以免存入无效的脏数据。
#8
╭═══╮ ╭═══╮ ╭══════╮
╰╮ ╭╯ ╰╮ ╭╯ ╰╮ ╭══╮╰╮
║ ║ ║ ║ ║ ║ ╰╮╰╮
║ ║ ║ ║ ║ ║ ║ ║
║ ║ ║ ║ ║ ║ ╭╯╭╯
║ ║ ║ ║ ║ ╰══╯╭╯
║ ║ ║ ║ ║ ╭═══╯
║ ║ ║ ║ ║ ║
╰╮╰╮ ╭╯╭╯ ║ ║
╰╮╰═╯╭╯ ╭╯ ╰╮
╰═══╯ ╰═══╯
╰╮ ╭╯ ╰╮ ╭╯ ╰╮ ╭══╮╰╮
║ ║ ║ ║ ║ ║ ╰╮╰╮
║ ║ ║ ║ ║ ║ ║ ║
║ ║ ║ ║ ║ ║ ╭╯╭╯
║ ║ ║ ║ ║ ╰══╯╭╯
║ ║ ║ ║ ║ ╭═══╯
║ ║ ║ ║ ║ ║
╰╮╰╮ ╭╯╭╯ ║ ║
╰╮╰═╯╭╯ ╭╯ ╰╮
╰═══╯ ╰═══╯
#9
将表里的数据提取出来放在一个datatable中,然后提取excel中数据,一个单元格放在一个表中一个item中,然后一起update....
#10
up!
#11
VB6的我做过!.Net没做过!帮楼主顶!顺便学习
#12
谢谢youlongzaitian(游龙在天)和3tzjq(不要轻言放弃!否则对不起自己) ,回头结贴给你们加分,但是最关键的错误处理过程好像代码不是很好写,望哪位大哥不吝赐教~:)
#13
up!
#14
/******* 导出到excel
EXEC master..xp_cmdshell 'bcp SettleDB.dbo.shanghu out c:temp1.xls -c -q -S"GNETDATA/GNETDATA" -U"sa" -P""'
/*********** 导入Excel
SELECT *
FROM OpenDataSource( 'Microsoft.Jet.OLEDB.4.0',
'Data Source="c:test.xls";User ID=Admin;Password=;Extended properties=Excel 5.0')...xactions
EXEC master..xp_cmdshell 'bcp SettleDB.dbo.shanghu out c:temp1.xls -c -q -S"GNETDATA/GNETDATA" -U"sa" -P""'
/*********** 导入Excel
SELECT *
FROM OpenDataSource( 'Microsoft.Jet.OLEDB.4.0',
'Data Source="c:test.xls";User ID=Admin;Password=;Extended properties=Excel 5.0')...xactions
#15
參考
5.
select * into 表 from OPENROWSET('MICROSOFT.JET.OLEDB.4.0'
,'Excel 5.0;HDR=YES;DATABASE=e:\test1.xls',sheet3$)
--无表头的时候,应该用:
insert into 表 select * from OPENROWSET('MICROSOFT.JET.OLEDB.4.0'
,'Excel 5.0;HDR=NO;DATABASE=c:\test.xls',sheet1$)
6.不用指定文件名,用下列語句,可以生成不存在的文件名,但Sheet名也為test3
EXEC master..xp_cmdshell 'bcp "SELECT class_no,kind_no,cn_name FROM new_ks.dbo.kind ORDER BY 1,2" queryout "e:\test3.xls" -c -q -S"sprogram" -U"develop" -P"12345"'
5.
select * into 表 from OPENROWSET('MICROSOFT.JET.OLEDB.4.0'
,'Excel 5.0;HDR=YES;DATABASE=e:\test1.xls',sheet3$)
--无表头的时候,应该用:
insert into 表 select * from OPENROWSET('MICROSOFT.JET.OLEDB.4.0'
,'Excel 5.0;HDR=NO;DATABASE=c:\test.xls',sheet1$)
6.不用指定文件名,用下列語句,可以生成不存在的文件名,但Sheet名也為test3
EXEC master..xp_cmdshell 'bcp "SELECT class_no,kind_no,cn_name FROM new_ks.dbo.kind ORDER BY 1,2" queryout "e:\test3.xls" -c -q -S"sprogram" -U"develop" -P"12345"'
#16
继续顶到有会处理异常的代码~还有80分
#17
关注,听说孟子E章会的哟,而且有现成的简单代码
#18
先读出来,再写入就可以的
#19
1.Add Reference Microsoft Excel 9.0 Object Libaray
2.
private Excel.Application ExcelObj = null;
public Form1()
{
// Initialize the Windows Components
InitializeComponent();
ExcelObj = new Excel.Application();
// See if the Excel Application Object was successfully constructed
if (ExcelObj == null)
{
MessageBox.Show("ERROR: EXCEL couldn't be started!");
System.Windows.Forms.Application.Exit();
}
// Make the Application Visible
ExcelObj.Visible = true;
}
private void menuItem2_Click(object sender, System.EventArgs e)
{
// prepare open file dialog to only search for excel files (had trouble setting this in design view)
this.openFileDialog1.FileName = "*.xls";
if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
{
// *********** Here is the call to Open a Workbook in Excel ****************
// It uses most of the default values (except for the read-only which we set to true)
Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open(
openFileDialog1.FileName, 0, true, 5,
"", "", true, Excel.XlPlatform.xlWindows, "\t", false, false,
0, true);
// get the collection of sheets in the workbook
Excel.Sheets sheets = theWorkbook.Worksheets;
// get the first and only worksheet from the collection
// of worksheets
Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1);
// loop through 10 rows of the spreadsheet and place each row in the list view
for (int i = 1; i <= 10; i++)
{
Excel.Range range = worksheet.get_Range("A"+i.ToString(), "J" + i.ToString());
System.Array myvalues = (System.Array)range.Cells.Value;
string[] strArray = ConvertToStringArray(myvalues);
listView1.Items.Add(new ListViewItem(strArray));
}
}
}
string[] ConvertToStringArray(System.Array values)
{
// create a new string array
string[] theArray = new string[values.Length];
// loop through the 2-D System.Array and populate the 1-D String Array
for (int i = 1; i <= values.Length; i++)
{
if (values.GetValue(1, i) == null)
theArray[i-1] = "";
else
theArray[i-1] = (string)values.GetValue(1, i).ToString();
}
return theArray;
}
2.
private Excel.Application ExcelObj = null;
public Form1()
{
// Initialize the Windows Components
InitializeComponent();
ExcelObj = new Excel.Application();
// See if the Excel Application Object was successfully constructed
if (ExcelObj == null)
{
MessageBox.Show("ERROR: EXCEL couldn't be started!");
System.Windows.Forms.Application.Exit();
}
// Make the Application Visible
ExcelObj.Visible = true;
}
private void menuItem2_Click(object sender, System.EventArgs e)
{
// prepare open file dialog to only search for excel files (had trouble setting this in design view)
this.openFileDialog1.FileName = "*.xls";
if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
{
// *********** Here is the call to Open a Workbook in Excel ****************
// It uses most of the default values (except for the read-only which we set to true)
Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open(
openFileDialog1.FileName, 0, true, 5,
"", "", true, Excel.XlPlatform.xlWindows, "\t", false, false,
0, true);
// get the collection of sheets in the workbook
Excel.Sheets sheets = theWorkbook.Worksheets;
// get the first and only worksheet from the collection
// of worksheets
Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1);
// loop through 10 rows of the spreadsheet and place each row in the list view
for (int i = 1; i <= 10; i++)
{
Excel.Range range = worksheet.get_Range("A"+i.ToString(), "J" + i.ToString());
System.Array myvalues = (System.Array)range.Cells.Value;
string[] strArray = ConvertToStringArray(myvalues);
listView1.Items.Add(new ListViewItem(strArray));
}
}
}
string[] ConvertToStringArray(System.Array values)
{
// create a new string array
string[] theArray = new string[values.Length];
// loop through the 2-D System.Array and populate the 1-D String Array
for (int i = 1; i <= values.Length; i++)
{
if (values.GetValue(1, i) == null)
theArray[i-1] = "";
else
theArray[i-1] = (string)values.GetValue(1, i).ToString();
}
return theArray;
}
#20
关注中!!!
#21
请参考
http://www.c-sharpcorner.com/winforms/ExcelReadMG.asp
http://www.yesky.com/20020313/1601534.shtml
http://www.c-sharpcorner.com/winforms/ExcelReadMG.asp
http://www.yesky.com/20020313/1601534.shtml
#22
但是最关键的错误处理过程好像代码不是很好写
什么错误处理过程呀?是往数据库中存储数据吗?
什么错误处理过程呀?是往数据库中存储数据吗?
#23
用SQL2000的DTS
#24
学习
#25
其实就是把excel文件做数据源,提取到一个dataset中,然后循环更新到数据库中,其中要用到事务。
要保证一致性。
至于错误,那就是普通的写log了。
要保证一致性。
至于错误,那就是普通的写log了。
#26
sql代码,搜索sql导入导出大全
出错的主要原因,就是excel的格式不对,有的单元格合并为标题了,
可是在关系数据库里就没法子表现出来
所以无论,怎么导出导入,都要先删去格式,转化为数据库能认识的咚咚
然后用sql代码实现
如果用datatable也可以,不过空转一回内存
出错的主要原因,就是excel的格式不对,有的单元格合并为标题了,
可是在关系数据库里就没法子表现出来
所以无论,怎么导出导入,都要先删去格式,转化为数据库能认识的咚咚
然后用sql代码实现
如果用datatable也可以,不过空转一回内存
#1
帮你顶,没有用过
#2
我只知道大概是...
先将Excel做为数据源加载到前台:
Dim str As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & Me.txt文件名.Text & ";" & _
"Extended Properties=""Excel 8.0;HDR=YES"""
Dim dcolink As New System.Data.OleDb.OleDbConnection(str)
Dim da As New System.Data.OleDb.OleDbDataAdapter("Select * From [Sheet1$]", dcolink)
Dim ds As New Data.DataSet()
da.Fill(ds, [Sheet1$]) '从Excel中导入的原始数据
然后用循环整个数据集的行,条件(重复信息或者唯一约束)成立的就Update...Insert...到数据库。
期待高手解答...
先将Excel做为数据源加载到前台:
Dim str As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & Me.txt文件名.Text & ";" & _
"Extended Properties=""Excel 8.0;HDR=YES"""
Dim dcolink As New System.Data.OleDb.OleDbConnection(str)
Dim da As New System.Data.OleDb.OleDbDataAdapter("Select * From [Sheet1$]", dcolink)
Dim ds As New Data.DataSet()
da.Fill(ds, [Sheet1$]) '从Excel中导入的原始数据
然后用循环整个数据集的行,条件(重复信息或者唯一约束)成立的就Update...Insert...到数据库。
期待高手解答...
#3
up,学习
#4
1。将EXCEL中数据先存进DATATALE,在将数据提取出来存进数据库就OK了!
2。在过程中采取事务捕捉异常!
2。在过程中采取事务捕捉异常!
#5
五楼能说具体点儿么?最好有点代码~
#6
Dim myConn As New OleDbConnection
Dim myAdaptor As New OleDbDataAdapter
Dim dt As New DataTable
Dim ds As New DataSet
Dim MyRow As DataRow
Dim strTemp As String
Dim i As Integer
Dim my_TableType As String '传入的文件类型
Dim strConn As String '连接字符
Dim strSql As String '查询字符
Dim strSplit As String '传入的文件名
Dim reader As StreamReader '定义IO流
Dim fs As FileStream '定义文件输出流
OpenFileDialog1.AddExtension = True
OpenFileDialog1.CheckFileExists = True
OpenFileDialog1.Title = "请选择要导入的文件"
OpenFileDialog1.Filter = "*.Excel文件|*.xls"
OpenFileDialog1.ShowDialog()
strSplit = OpenFileDialog1.FileName
my_TableType = Microsoft.VisualBasic.Right(strSplit, 4)
Dim ArrCSC As Array
Dim intCSC As Integer
Dim strCSC As String
If my_TableType = ".xls" Or my_TableType = ".XLS" Then
If txtCSCID.Text = "" Then
ArrCSC = Split(strSplit, "\")
intCSC = ArrCSC.Length
strCSC = ArrCSC(intCSC - 1)
strCSC = Microsoft.VisualBasic.Left(strCSC, strCSC.Length - 4)
cmbCSCName.Text = strCSC
Dim Showup As New Client
Showup.CSC_Name = Trim(cmbCSCName.Text) '获得客户名称
Showup.getCSCDetailByName(Showup.CSC_Name) '获取客户的详细情况
txtCSCID.Text = Showup.CSC_ID
txtAddress.Text = Showup.Address
txtTel.Text = Showup.Tel
txtLinkMan.Text = Showup.LinkMan
txtZip.Text = Showup.Zip
txtFax.Text = Showup.Fax
cmbCSCName.Enabled = False
cmbCSCName.BackColor = New Color
txtEMail.Text = Showup.Email
'Showup.getCS(Showup.CSC_Name)
'txtCSName.Text = Showup.CS
'txtCSID.Text = Showup.CSID
End If
'导入excel文件
Dim MyFalut As New Fault
Dim MyProduct As New Product
Dim MyMaterial As New Material
Dim MyLLBLLX As New LLBLLX
Dim MyUnitsType As New HandGet
Try
GetOperateLog(9522)
strConn = "provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;data source=" + strSplit + ""
strSql = "Select * From[sheet1$]"
myConn = New OleDbConnection(strConn)
myConn.Open()
myAdaptor = New OleDbDataAdapter(strSql, myConn)
myAdaptor.Fill(ds, "ExcelData")
dt = ds.Tables(0)
For i = 0 To dt.Rows.Count - 1
MyRow = MyDataTable.NewRow
MyRow(2) = dt.Rows(i).Item("物料类型")
If IsDBNull(MyRow(2)) = False Then
MyUnitsType.GetUnitsType_ID(Trim(dt.Rows(i).Item("物料类型")))
MyRow(1) = MyUnitsType.UnitType_Id
Else
MyRow(1) = DBNull.Value
End If
MyRow(3) = dt.Rows(i).Item("条形码")
MyRow(4) = dt.Rows(i).Item("物料名称")
If IsDBNull(MyRow(4)) = False Then
MyMaterial.GetUnits_ID(Trim(dt.Rows(i).Item("物料名称"))) '传递物料名称
MyRow(5) = MyMaterial.Units_ID
Else
MyRow(5) = DBNull.Value
End If
MyRow(7) = dt.Rows(i).Item("小灵通机型")
If IsDBNull(dt.Rows(i).Item("小灵通机型")) = False Then
MyProduct.GetProductID(Trim(dt.Rows(i).Item("小灵通机型"))) '传递机型名称
MyRow(6) = MyProduct.Product_ID
Else
MyRow(6) = DBNull.Value
MyRow(7) = ""
End If
MyRow(8) = dt.Rows(i).Item("小灵通号码")
MyRow(9) = dt.Rows(i).Item("购买时间")
MyRow(10) = dt.Rows(i).Item("投诉时间")
MyRow(11) = dt.Rows(i).Item("用户姓名")
MyRow(12) = dt.Rows(i).Item("联系电话")
MyRow(13) = dt.Rows(i).Item("送修人")
MyRow(14) = dt.Rows(i).Item("送修人电话")
MyRow(16) = dt.Rows(i).Item("故障类型")
If IsDBNull(MyRow(16)) = False Then
MyFalut.GetFaultName(Trim(dt.Rows(i).Item("故障类型"))) '传递故障名称
MyRow(15) = MyFalut.Fault_ID
Else
MyRow(15) = DBNull.Value
End If
MyRow(17) = dt.Rows(i).Item("故障描述")
MyRow(18) = dt.Rows(i).Item("是否保修")
MyRow(19) = dt.Rows(i).Item("是否来料不良")
MyRow(21) = dt.Rows(i).Item("来料不良类型")
If IsDBNull(MyRow(21)) = False Then
MyLLBLLX.GetLLBLLXID(Trim(dt.Rows(i).Item("来料不良类型"))) '传递来料不良名称
MyRow(20) = MyLLBLLX.LLBLLX_ID
Else
MyRow(20) = DBNull.Value
End If
MyRow(22) = dt.Rows(i).Item("是否是SP")
MyRow(23) = dt.Rows(i).Item("SP名称")
MyRow(24) = dt.Rows(i).Item("是否是大客户")
MyDataTable.Rows.Add(MyRow)
Next
Catch ex As Exception
Dim exm As String = ex.Message
GetErrLog(ex)
MessageBox.Show("系统执行时发生以下错误:" + vbCrLf.ToString + "错误源:" + ex.Source.ToString.ToString + vbCrLf.ToString + "错误信息:" + ex.Message.ToString + vbCrLf.ToString + vbCrLf.ToString + "请记录错误信息,并与管理员联系。", "PurpleStar", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)
Finally
myConn.Close()
myConn = Nothing
End Try
Else
Exit Sub
End If
这是将数据从EXCEL读出显示在DATAGRID里的,剩下的部分我手头没有源码,不好意思!
Dim myAdaptor As New OleDbDataAdapter
Dim dt As New DataTable
Dim ds As New DataSet
Dim MyRow As DataRow
Dim strTemp As String
Dim i As Integer
Dim my_TableType As String '传入的文件类型
Dim strConn As String '连接字符
Dim strSql As String '查询字符
Dim strSplit As String '传入的文件名
Dim reader As StreamReader '定义IO流
Dim fs As FileStream '定义文件输出流
OpenFileDialog1.AddExtension = True
OpenFileDialog1.CheckFileExists = True
OpenFileDialog1.Title = "请选择要导入的文件"
OpenFileDialog1.Filter = "*.Excel文件|*.xls"
OpenFileDialog1.ShowDialog()
strSplit = OpenFileDialog1.FileName
my_TableType = Microsoft.VisualBasic.Right(strSplit, 4)
Dim ArrCSC As Array
Dim intCSC As Integer
Dim strCSC As String
If my_TableType = ".xls" Or my_TableType = ".XLS" Then
If txtCSCID.Text = "" Then
ArrCSC = Split(strSplit, "\")
intCSC = ArrCSC.Length
strCSC = ArrCSC(intCSC - 1)
strCSC = Microsoft.VisualBasic.Left(strCSC, strCSC.Length - 4)
cmbCSCName.Text = strCSC
Dim Showup As New Client
Showup.CSC_Name = Trim(cmbCSCName.Text) '获得客户名称
Showup.getCSCDetailByName(Showup.CSC_Name) '获取客户的详细情况
txtCSCID.Text = Showup.CSC_ID
txtAddress.Text = Showup.Address
txtTel.Text = Showup.Tel
txtLinkMan.Text = Showup.LinkMan
txtZip.Text = Showup.Zip
txtFax.Text = Showup.Fax
cmbCSCName.Enabled = False
cmbCSCName.BackColor = New Color
txtEMail.Text = Showup.Email
'Showup.getCS(Showup.CSC_Name)
'txtCSName.Text = Showup.CS
'txtCSID.Text = Showup.CSID
End If
'导入excel文件
Dim MyFalut As New Fault
Dim MyProduct As New Product
Dim MyMaterial As New Material
Dim MyLLBLLX As New LLBLLX
Dim MyUnitsType As New HandGet
Try
GetOperateLog(9522)
strConn = "provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;data source=" + strSplit + ""
strSql = "Select * From[sheet1$]"
myConn = New OleDbConnection(strConn)
myConn.Open()
myAdaptor = New OleDbDataAdapter(strSql, myConn)
myAdaptor.Fill(ds, "ExcelData")
dt = ds.Tables(0)
For i = 0 To dt.Rows.Count - 1
MyRow = MyDataTable.NewRow
MyRow(2) = dt.Rows(i).Item("物料类型")
If IsDBNull(MyRow(2)) = False Then
MyUnitsType.GetUnitsType_ID(Trim(dt.Rows(i).Item("物料类型")))
MyRow(1) = MyUnitsType.UnitType_Id
Else
MyRow(1) = DBNull.Value
End If
MyRow(3) = dt.Rows(i).Item("条形码")
MyRow(4) = dt.Rows(i).Item("物料名称")
If IsDBNull(MyRow(4)) = False Then
MyMaterial.GetUnits_ID(Trim(dt.Rows(i).Item("物料名称"))) '传递物料名称
MyRow(5) = MyMaterial.Units_ID
Else
MyRow(5) = DBNull.Value
End If
MyRow(7) = dt.Rows(i).Item("小灵通机型")
If IsDBNull(dt.Rows(i).Item("小灵通机型")) = False Then
MyProduct.GetProductID(Trim(dt.Rows(i).Item("小灵通机型"))) '传递机型名称
MyRow(6) = MyProduct.Product_ID
Else
MyRow(6) = DBNull.Value
MyRow(7) = ""
End If
MyRow(8) = dt.Rows(i).Item("小灵通号码")
MyRow(9) = dt.Rows(i).Item("购买时间")
MyRow(10) = dt.Rows(i).Item("投诉时间")
MyRow(11) = dt.Rows(i).Item("用户姓名")
MyRow(12) = dt.Rows(i).Item("联系电话")
MyRow(13) = dt.Rows(i).Item("送修人")
MyRow(14) = dt.Rows(i).Item("送修人电话")
MyRow(16) = dt.Rows(i).Item("故障类型")
If IsDBNull(MyRow(16)) = False Then
MyFalut.GetFaultName(Trim(dt.Rows(i).Item("故障类型"))) '传递故障名称
MyRow(15) = MyFalut.Fault_ID
Else
MyRow(15) = DBNull.Value
End If
MyRow(17) = dt.Rows(i).Item("故障描述")
MyRow(18) = dt.Rows(i).Item("是否保修")
MyRow(19) = dt.Rows(i).Item("是否来料不良")
MyRow(21) = dt.Rows(i).Item("来料不良类型")
If IsDBNull(MyRow(21)) = False Then
MyLLBLLX.GetLLBLLXID(Trim(dt.Rows(i).Item("来料不良类型"))) '传递来料不良名称
MyRow(20) = MyLLBLLX.LLBLLX_ID
Else
MyRow(20) = DBNull.Value
End If
MyRow(22) = dt.Rows(i).Item("是否是SP")
MyRow(23) = dt.Rows(i).Item("SP名称")
MyRow(24) = dt.Rows(i).Item("是否是大客户")
MyDataTable.Rows.Add(MyRow)
Next
Catch ex As Exception
Dim exm As String = ex.Message
GetErrLog(ex)
MessageBox.Show("系统执行时发生以下错误:" + vbCrLf.ToString + "错误源:" + ex.Source.ToString.ToString + vbCrLf.ToString + "错误信息:" + ex.Message.ToString + vbCrLf.ToString + vbCrLf.ToString + "请记录错误信息,并与管理员联系。", "PurpleStar", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)
Finally
myConn.Close()
myConn = Nothing
End Try
Else
Exit Sub
End If
这是将数据从EXCEL读出显示在DATAGRID里的,剩下的部分我手头没有源码,不好意思!
#7
其实上面的代码已经实现了将EXCEL数据存储在DATATABLE里的功能,你现在只要对DATATABLE依次循环取值,在逐条存进数据库OK了,最好将从DATATABLE取出数据存入数据库的过程加在TRY和CATCH之间,这样便于捕捉异常。还有在存储数据到数据库时要加事务,以免存入无效的脏数据。
#8
╭═══╮ ╭═══╮ ╭══════╮
╰╮ ╭╯ ╰╮ ╭╯ ╰╮ ╭══╮╰╮
║ ║ ║ ║ ║ ║ ╰╮╰╮
║ ║ ║ ║ ║ ║ ║ ║
║ ║ ║ ║ ║ ║ ╭╯╭╯
║ ║ ║ ║ ║ ╰══╯╭╯
║ ║ ║ ║ ║ ╭═══╯
║ ║ ║ ║ ║ ║
╰╮╰╮ ╭╯╭╯ ║ ║
╰╮╰═╯╭╯ ╭╯ ╰╮
╰═══╯ ╰═══╯
╰╮ ╭╯ ╰╮ ╭╯ ╰╮ ╭══╮╰╮
║ ║ ║ ║ ║ ║ ╰╮╰╮
║ ║ ║ ║ ║ ║ ║ ║
║ ║ ║ ║ ║ ║ ╭╯╭╯
║ ║ ║ ║ ║ ╰══╯╭╯
║ ║ ║ ║ ║ ╭═══╯
║ ║ ║ ║ ║ ║
╰╮╰╮ ╭╯╭╯ ║ ║
╰╮╰═╯╭╯ ╭╯ ╰╮
╰═══╯ ╰═══╯
#9
将表里的数据提取出来放在一个datatable中,然后提取excel中数据,一个单元格放在一个表中一个item中,然后一起update....
#10
up!
#11
VB6的我做过!.Net没做过!帮楼主顶!顺便学习
#12
谢谢youlongzaitian(游龙在天)和3tzjq(不要轻言放弃!否则对不起自己) ,回头结贴给你们加分,但是最关键的错误处理过程好像代码不是很好写,望哪位大哥不吝赐教~:)
#13
up!
#14
/******* 导出到excel
EXEC master..xp_cmdshell 'bcp SettleDB.dbo.shanghu out c:temp1.xls -c -q -S"GNETDATA/GNETDATA" -U"sa" -P""'
/*********** 导入Excel
SELECT *
FROM OpenDataSource( 'Microsoft.Jet.OLEDB.4.0',
'Data Source="c:test.xls";User ID=Admin;Password=;Extended properties=Excel 5.0')...xactions
EXEC master..xp_cmdshell 'bcp SettleDB.dbo.shanghu out c:temp1.xls -c -q -S"GNETDATA/GNETDATA" -U"sa" -P""'
/*********** 导入Excel
SELECT *
FROM OpenDataSource( 'Microsoft.Jet.OLEDB.4.0',
'Data Source="c:test.xls";User ID=Admin;Password=;Extended properties=Excel 5.0')...xactions
#15
參考
5.
select * into 表 from OPENROWSET('MICROSOFT.JET.OLEDB.4.0'
,'Excel 5.0;HDR=YES;DATABASE=e:\test1.xls',sheet3$)
--无表头的时候,应该用:
insert into 表 select * from OPENROWSET('MICROSOFT.JET.OLEDB.4.0'
,'Excel 5.0;HDR=NO;DATABASE=c:\test.xls',sheet1$)
6.不用指定文件名,用下列語句,可以生成不存在的文件名,但Sheet名也為test3
EXEC master..xp_cmdshell 'bcp "SELECT class_no,kind_no,cn_name FROM new_ks.dbo.kind ORDER BY 1,2" queryout "e:\test3.xls" -c -q -S"sprogram" -U"develop" -P"12345"'
5.
select * into 表 from OPENROWSET('MICROSOFT.JET.OLEDB.4.0'
,'Excel 5.0;HDR=YES;DATABASE=e:\test1.xls',sheet3$)
--无表头的时候,应该用:
insert into 表 select * from OPENROWSET('MICROSOFT.JET.OLEDB.4.0'
,'Excel 5.0;HDR=NO;DATABASE=c:\test.xls',sheet1$)
6.不用指定文件名,用下列語句,可以生成不存在的文件名,但Sheet名也為test3
EXEC master..xp_cmdshell 'bcp "SELECT class_no,kind_no,cn_name FROM new_ks.dbo.kind ORDER BY 1,2" queryout "e:\test3.xls" -c -q -S"sprogram" -U"develop" -P"12345"'
#16
继续顶到有会处理异常的代码~还有80分
#17
关注,听说孟子E章会的哟,而且有现成的简单代码
#18
先读出来,再写入就可以的
#19
1.Add Reference Microsoft Excel 9.0 Object Libaray
2.
private Excel.Application ExcelObj = null;
public Form1()
{
// Initialize the Windows Components
InitializeComponent();
ExcelObj = new Excel.Application();
// See if the Excel Application Object was successfully constructed
if (ExcelObj == null)
{
MessageBox.Show("ERROR: EXCEL couldn't be started!");
System.Windows.Forms.Application.Exit();
}
// Make the Application Visible
ExcelObj.Visible = true;
}
private void menuItem2_Click(object sender, System.EventArgs e)
{
// prepare open file dialog to only search for excel files (had trouble setting this in design view)
this.openFileDialog1.FileName = "*.xls";
if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
{
// *********** Here is the call to Open a Workbook in Excel ****************
// It uses most of the default values (except for the read-only which we set to true)
Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open(
openFileDialog1.FileName, 0, true, 5,
"", "", true, Excel.XlPlatform.xlWindows, "\t", false, false,
0, true);
// get the collection of sheets in the workbook
Excel.Sheets sheets = theWorkbook.Worksheets;
// get the first and only worksheet from the collection
// of worksheets
Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1);
// loop through 10 rows of the spreadsheet and place each row in the list view
for (int i = 1; i <= 10; i++)
{
Excel.Range range = worksheet.get_Range("A"+i.ToString(), "J" + i.ToString());
System.Array myvalues = (System.Array)range.Cells.Value;
string[] strArray = ConvertToStringArray(myvalues);
listView1.Items.Add(new ListViewItem(strArray));
}
}
}
string[] ConvertToStringArray(System.Array values)
{
// create a new string array
string[] theArray = new string[values.Length];
// loop through the 2-D System.Array and populate the 1-D String Array
for (int i = 1; i <= values.Length; i++)
{
if (values.GetValue(1, i) == null)
theArray[i-1] = "";
else
theArray[i-1] = (string)values.GetValue(1, i).ToString();
}
return theArray;
}
2.
private Excel.Application ExcelObj = null;
public Form1()
{
// Initialize the Windows Components
InitializeComponent();
ExcelObj = new Excel.Application();
// See if the Excel Application Object was successfully constructed
if (ExcelObj == null)
{
MessageBox.Show("ERROR: EXCEL couldn't be started!");
System.Windows.Forms.Application.Exit();
}
// Make the Application Visible
ExcelObj.Visible = true;
}
private void menuItem2_Click(object sender, System.EventArgs e)
{
// prepare open file dialog to only search for excel files (had trouble setting this in design view)
this.openFileDialog1.FileName = "*.xls";
if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
{
// *********** Here is the call to Open a Workbook in Excel ****************
// It uses most of the default values (except for the read-only which we set to true)
Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open(
openFileDialog1.FileName, 0, true, 5,
"", "", true, Excel.XlPlatform.xlWindows, "\t", false, false,
0, true);
// get the collection of sheets in the workbook
Excel.Sheets sheets = theWorkbook.Worksheets;
// get the first and only worksheet from the collection
// of worksheets
Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1);
// loop through 10 rows of the spreadsheet and place each row in the list view
for (int i = 1; i <= 10; i++)
{
Excel.Range range = worksheet.get_Range("A"+i.ToString(), "J" + i.ToString());
System.Array myvalues = (System.Array)range.Cells.Value;
string[] strArray = ConvertToStringArray(myvalues);
listView1.Items.Add(new ListViewItem(strArray));
}
}
}
string[] ConvertToStringArray(System.Array values)
{
// create a new string array
string[] theArray = new string[values.Length];
// loop through the 2-D System.Array and populate the 1-D String Array
for (int i = 1; i <= values.Length; i++)
{
if (values.GetValue(1, i) == null)
theArray[i-1] = "";
else
theArray[i-1] = (string)values.GetValue(1, i).ToString();
}
return theArray;
}
#20
关注中!!!
#21
请参考
http://www.c-sharpcorner.com/winforms/ExcelReadMG.asp
http://www.yesky.com/20020313/1601534.shtml
http://www.c-sharpcorner.com/winforms/ExcelReadMG.asp
http://www.yesky.com/20020313/1601534.shtml
#22
但是最关键的错误处理过程好像代码不是很好写
什么错误处理过程呀?是往数据库中存储数据吗?
什么错误处理过程呀?是往数据库中存储数据吗?
#23
用SQL2000的DTS
#24
学习
#25
其实就是把excel文件做数据源,提取到一个dataset中,然后循环更新到数据库中,其中要用到事务。
要保证一致性。
至于错误,那就是普通的写log了。
要保证一致性。
至于错误,那就是普通的写log了。
#26
sql代码,搜索sql导入导出大全
出错的主要原因,就是excel的格式不对,有的单元格合并为标题了,
可是在关系数据库里就没法子表现出来
所以无论,怎么导出导入,都要先删去格式,转化为数据库能认识的咚咚
然后用sql代码实现
如果用datatable也可以,不过空转一回内存
出错的主要原因,就是excel的格式不对,有的单元格合并为标题了,
可是在关系数据库里就没法子表现出来
所以无论,怎么导出导入,都要先删去格式,转化为数据库能认识的咚咚
然后用sql代码实现
如果用datatable也可以,不过空转一回内存