[英]Import Excel data to DataBase dynamically
我可能想知道標題的方式,我想知道一種將數據從excel導入數據庫的方法,盡管我讀了很多有關此問題的答案,但我找不到能解決我問題的方法。 因此,我的excel工作表每分鍾刷新一次其數字(通過從互聯網獲取新值並覆蓋同一單元格),因此excel需要始終打開。 我想從Visual Studio中讀取這些值,獲取這些值並將其寫入我的數據庫中。 我已經使用OleDb並在PostgreSql上編寫了它,但是它僅在我的excel關閉時才有效(我認為那樣是因為OleDb打開excel才能讀取它,並且說它已經被打開了,所以不起作用)。 我真的很感謝任何能幫助我的人……謝謝!
我想從Visual Studio中讀取這些值
VBA為什么不讀取這些值並寫入Postgres? 您可以在Excel工作簿中運行VBA宏。 例如:
Sub Cell2Postgres()
Dim Connection As New ADODB.Connection
Dim Command As New ADODB.Command
Connection.ConnectionString = "Driver=PostgreSQL Unicode;Server=localhost;Port=5432;Database=postgres;Uid=postgres;Pwd=postgres"
Connection.Open
Command.ActiveConnection = Connection
Command.CommandText = "INSERT INTO public.mytable (myfield) VALUES (?)"
Command.Parameters.Append Command.CreateParameter("", adVarChar, adParamInput, 255, Range("A1").Value)
Command.Execute
Connection.Close
End Sub
這是我為外接程序編寫的一些代碼,它確實做到了-在Excel中使用突出顯示的范圍並將其上載到表(在這種情況下,使用C#和VSTO)。
這段代碼經過了許多次迭代,最后我們很滿意。 它非常快(比我們之前嘗試的任何版本都要快,並且比PgAdmin的導入要快),並且對數據類型非常寬容-您甚至不需要知道目標表的數據類型,只要以這種方式設置格式即可PostgresSQL的copy
命令可以加載它。
簡而言之,它接受范圍,將特殊值復制粘貼到新工作表,將工作表另存為CSV(快速,使用本機Excel功能),壓縮CSV文件,將文件通過FTP傳輸到PostgreSQL服務器,然后運行copy
命令。
CAVEAT:因為這確實是copy
,所以實際運行命令的用戶必須是超級用戶。
var addIn = Globals.ThisAddIn;
Excel.Range range = addIn.Application.Selection;
Excel.Workbook wb = addIn.Application.Workbooks.Add();
Excel.Worksheet ws = wb.Worksheets[1];
range.Copy();
ws.get_Range("A1").PasteSpecial(Excel.XlPasteType.xlPasteValuesAndNumberFormats);
addIn.Application.DisplayAlerts = false;
wb.SaveAs(Path.Combine(_Outputdir, string.Format("{0}.csv", TableName)),
Excel.XlFileFormat.xlCSV);
wb.Close();
addIn.Application.DisplayAlerts = true;
string newFile = Commons.Compress(_Outputdir, string.Format("{0}.csv", TableName));
這是我們編寫的自定義FTP例程。 我無法使.NET類庫正常工作。 您可以執行任何您想將其發送到服務器的操作:
Commons.FtpPut(newFile, _Outputdir);
現在,加載數據:
NpgsqlTransaction trans = conn.BeginTransaction(IsolationLevel.RepeatableRead);
if (TruncateTable)
{
cmd = new NpgsqlCommand(string.Format("truncate table {0}", TableName), conn, trans);
cmd.ExecuteNonQuery();
}
try
{
Stopwatch st = new Stopwatch();
st.Start();
string format = HasHeader ? "csv header" : "csv";
cmd.CommandText = string.Format(
"copy {0} from program 'gzip -dc /apps/external_data/inbound/{0}.csv.gz' " +
"with null as '' {1} encoding 'WIN1250'", TableName, format);
cmd.ExecuteNonQuery();
trans.Commit();
st.Stop();
Results = string.Format("Upload Completed in {0}", st.Elapsed);
}
catch (Exception ex)
{
trans.Rollback();
Results = ex.ToString();
success = false;
}
同樣,手動滾動自己的FTP清理過程:
Commons.FtpDelete(newFile, _Outputdir);
在此之前,我們進行檢查以確保用戶具有截斷和/或加載表的權限。
最后一點-此代碼不是名義上的。 它在生產中運行,用戶每天要進行數十次表格上傳。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.