如何读取、编辑和写入xls文件,然后导出到SQL Server
我有一个 Excel 文件,其中包含我需要推送到 SQL Server 数据库中的联系人列表(大约 10k)。因此,我正在使用 Visual Studio 2008 编写一个 .net Windows 程序来读取文件,为每个联系人生成随机密码,然后将这些信息推送到我的 SQL Server 数据库中。
2003 年处理 Excel 文件很容易,但现在我的电脑里装了 Office 2007,情况似乎发生了变化。我正在研究 Microsoft.Office.Interop.Excel,但它似乎比以前复杂得多。
I have an excel file that have the list of contacts (about 10 k of them) that I need to push into my SQL Server database. So, I am writing an .net windows program using visual studio 2008 to read the files, generate random password for each contact, and then push these information in to my SQL Server database.
It was easy to handle excel file in 2003 but now my computer have office 2007 in it and things seem to changed. I am digging on Microsoft.Office.Interop.Excel but it is seem to be a lot more complicated than before.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果这是一次性交易,您只需稍微格式化 Excel 文件,将其导入并访问数据库,然后将其推回到您想要的任何数据库。
如果你必须在.net中执行此操作,你可以使用SQL通过ODBC打开一个excel文件...它有点脆弱,但我过去已经成功地使用过它。
在 Excel 中使用类似的连接字符串:
提供商=Microsoft.Jet.OLEDB.4.0;数据源=C:\MyExcel.xls;扩展属性=“Excel 8.0;HDR=是;IMEX=1”;
工作表和命名部分是表名称。HDR=Yes 表示第一行包含字段名称。我承认这有点奇怪。 :)
If it is a one shot kind of deal, you could just format the excel file a little, import that into and access database and then push that back to any database you want.
If you must do it in .net, you can open a excel file through ODBC using SQL...It is a little fragile, but I've used it with success in the past.
Use something like this for a connection string in excel :
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\MyExcel.xls;Extended Properties="Excel 8.0;HDR=Yes;IMEX=1";
The worksheet and named section are the table names..HDR=Yes mean that the first row contains the name of the fields. I'll admit it is a little odd. :)
我会采用 ETL 方法来实现这一点:
如果这是需要一遍又一遍地完成的事情,我会将包保存到 SQL Server 中,并从我的 C# 程序中调用它。
I would take an ETL approach to this:
If this is something that needs to be done over and over again, I would save the package into SQL Server, and call it from my C# program.
我不确定这是否对您有帮助,但也许 SSIS(SQL Server 集成服务)会对您有所帮助。
除此之外,您可以尝试在 Excel 中录制宏,同时在 Excel 中执行所需的操作,完成操作后,您可以查看录制的宏 (ALT + F8) 并将其“翻译”到您的 .NET 代码中。
只是一个建议。
I'm not sure if this will help you, but maybe SSIS (SQL Server Integration Services) would help you.
Apart from that you could try recording a macro in Excel while performing your desired manipulations in Excel and when you are done with your manipulations you could take a look at the recorded macro (ALT + F8) and 'translate' it into your .NET code.
Just a suggestion.