我有一個vb.net函數,它使用oledb創建一個電子表格,然後把它當作一個數據庫,創建表格和插入值。該函數接受一個文件名和一個數據集,並在文件名返回時返回文件名。該功能在我的開發機器上很好地工作,但不是其他PC。下面是我的功能,代碼有什麼問題嗎?有什麼建議麼?vb.net寫作excel函數在一個pc上工作,但不在另一個
編輯:沒有錯誤被拋出,結果文件不包含任何數據。
Imports System
Imports System.Configuration
Imports System.Data
Imports System.Data.OleDb
Imports System.Data.SqlClient
Imports System.Drawing
Imports System.IO
Imports System.Net.Mail
Imports System.Text
Imports System.Web
Imports Microsoft.Office.Interop
....
Public Shared Function writeToExcelFile(ByVal template As String, ByVal filename As String, ByVal data As DataSet) As String
If File.Exists(filename) Then
File.Delete(filename)
End If
If template <> String.Empty AndAlso filename <> String.Empty Then
File.Copy(template, filename)
End If
Dim connString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filename + ";Extended Properties=""Excel 8.0;HDR=Yes;"""
Dim conn As New OleDbConnection(connString)
Try
conn.Open()
Dim cmd As New OleDbCommand()
For Each table As DataTable In data.Tables
Dim tableName As String = table.TableName.Replace(" ", "")
Dim tableCreate As String = "CREATE TABLE [" + tableName + "] ("
Dim sql As String = "INSERT INTO [" + tableName + "$]("
Dim colName As String = String.Empty
For Each col As DataColumn In table.Columns
colName = col.ColumnName.Replace("#", "num")
If colName.Contains(" ") Then
sql += " [" + colName.Replace("'", "") + "],"
Else
sql += " " + colName.Replace("'", "") + ","
End If
tableCreate += " [" + colName + "] varchar(255),"
Next
If tableCreate.EndsWith(",") Then
tableCreate = tableCreate.TrimEnd(New [Char]() {","c})
End If
tableCreate += ") "
cmd = New OleDbCommand(tableCreate, conn)
cmd.ExecuteNonQuery()
If sql.EndsWith(",") Then
sql = sql.TrimEnd(New [Char]() {","c})
End If
sql += ") "
For Each row As DataRow In table.Rows
Dim values As String = " VALUES("
For Each col As DataColumn In table.Columns
Try
values += "'" + cleanString(row(col).ToString()).Substring(0, 250) + "...',"
Catch e As Exception
values += "'" + cleanString(row(col).ToString()) + "',"
End Try
Next
If values.EndsWith(",") Then
values = values.TrimEnd(New [Char]() {","c})
End If
values += ") "
cmd = New OleDbCommand(sql + values, conn)
cmd.ExecuteNonQuery()
Next
Next
conn.Close()
Return filename
Catch e As Exception
Throw New Exception(e.Message)
Return String.Empty
End Try
End Function
是否引發了任何錯誤? – N0Alias 2011-03-29 19:32:19
請參閱上面的編輯。 – MAW74656 2011-03-29 19:33:31
(1)在你的catch塊中返回或拋出,你不能同時執行這兩個操作。 (2)其他用途是否具有相同版本的Excel? (3)他們是否具有讀取和寫入文件和模板的正確權限,舊文件是否被刪除? (4)您是否可以添加更多日誌記錄以準確找出目標系統上發生的情況? – 2011-03-29 19:44:43