将Excel数据dynamic导入到数据库

你怎么可能看到的标题,我想知道一种方法来从Excel中导入数据到数据库,即使我读了很多的问题和答案,我没有find一个可以解决我的问题。 所以我的Excel表格每分钟刷新一次(通过从互联网获取新值并覆盖同一个单元格),所以需要始终打开Excel。 我想从Visual Studio中读取这些值,获取这些值并将其写入我的数据库。 我已经得到了使用OleDb并将其写入PostgreSQL的工作,但它只适用于我的Excel是closures的(我认为就是这样,因为OleDb打开Excel读取,它已经打开,它不工作)。 我真的很感激任何人可以帮助我…谢谢!

…我想从视觉工作室读取这些值…

为什么不VBA读取这些值并写入Postgres? 您可以在Excel工作簿中运行VBAmacros。 例如:

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的导入更快),并且非常容忍数据types – 如果您以某种方式格式化目标表的数据types,您甚至不需要知道目标表的数据typesPostgresSQL的copy命令可以加载它。

简而言之,它需要一个范围,将一个特殊值复制粘贴到一个新的工作表中,将工作表保存为CSV(Fast,使用本地Excelfunction),压缩CSV文件,将文件传送到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); 

在此之上,我们进行检查以确保用户有权限截断和/或加载表。

最后一个注意事项 – 这个代码不是名义上的。 它运行在生产环境中,用户每天上传数十个表格。