简体   繁体   English

将csv文件/ excel导入sql数据库asp.net

[英]import csv file/excel into sql database asp.net

I am starting a project with asp.net visual studio 2008 / SQL 2000 (2005 in future) using c#. 我正在使用c#启动asp.net visual studio 2008 / SQL 2000(将来的2005)项目。

The tricky part for me is that the existing DB schema changes often and the import files columns will all have to be matched up with the existing db schema since they may not be one to one match on column names. 对我来说棘手的部分是现有的数据库模式经常更改,导入文件列都必须与现有的数据库模式匹配,因为它们可能不是列名称上的一对一匹配。 (There is a lookup table that provides the tables schema with column names I will use) (有一个查找表,它提供了我将使用的列名称的表模式)

I am exploring different ways to approach this, and need some expert advice. 我正在探索不同的方法来解决这个问题,需要一些专家建议。 Is there any existing controls or frameworks that I can leverage to do any of this? 是否有任何现有的控件或框架可用于执行此操作?

So far I explored FileUpload .NET control, as well as some 3rd party upload controls to accomplish the upload such as SlickUpload but the files uploaded should be < 500mb 到目前为止,我探索了FileUpload .NET控件,以及一些第三方上传控件来完成上传,如SlickUpload,但上传的文件应<500mb

Next part is reading of my csv /excel and parsing it for display to the user so they can match it with our db schema. 下一部分是读取我的csv / excel并解析它以显示给用户,以便它们可以与我们的db模式匹配。 I saw CSVReader and others but for excel its more difficult since I will need to support different versions. 我看过CSVReader和其他人,但是因为我需要支持不同的版本,所以更难以实现。

Essentially The user performing this import will insert and/or update several tables from this import file. 实质上执行此导入的用户将从此导入文件中插入和/或更新多个表。 There are other more advance requirements like record matching but and preview of the import records, but I wish to get through understanding how to do this first. 还有其他更先进的要求,如记录匹配,但预览导入记录,但我希望首先了解如何执行此操作。

Update: I ended up using csvReader with LumenWorks.Framework for uploading the csv files. 更新:我最终使用csvReader和LumenWorks.Framework上传csv文件。

Check out the excellent FileHelpers library - there an article on CodeProject about it, and it's hosted here . 查看优秀的FileHelpers库 - 有一篇关于它的CodeProject文章 ,它在这里托管。

It's pure C#, and it can import just about any flat-file, CSV, and it deals with Excel, too. 它是纯粹的C#,它可以导入任何平面文件,CSV,它也可以处理Excel。 The import is totally configurable - you can define things like delimiters, rows and/or columns to skip, and so on - lots of options. 导入是完全可配置的 - 您可以定义要跳过的分隔符,行和/或列等内容 - 许多选项。

I've successfully used it in various projects and it just works flawlessly - highly recommended. 我已成功地在各种项目中使用它,它只是完美无缺 - 非常值得推荐。

You can easily create an IDataReader over an Excel or CSV file (see http://support.microsoft.com/kb/316934 ). 您可以轻松地在Excel或CSV文件上创建IDataReader(请参阅http://support.microsoft.com/kb/316934 )。

Are you using SQL Server as your database engine? 您使用SQL Server作为数据库引擎吗? If so, you can use the SqlBulkCopy class ( http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.aspx ) to efficiently take your IDataReader, map columns as appropriate, and store the results in your database. 如果是这样,您可以使用SqlBulkCopy类( http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.aspx )有效地获取IDataReader,根据需要映射列,并存储结果在您的数据库中。

I suspect there may exist some robust and flexible tools to help you with this potentially very complex application that hopefully someone will point you to. 我怀疑可能存在一些强大而灵活的工具来帮助您处理这个可能非常复杂的应用程序,希望有人能指出这一点。

In the mean time, here is a function I have found useful to covert an excel file to a DataTable. 同时,这里有一个我发现有用的功能可以将excel文件转换为DataTable。 This version only looks for the first worksheet. 此版本仅查找第一个工作表。 It might serve as a starting point. 它可以作为一个起点。 To to something similar with csv files should only require modifying the connection string. 要与csv文件类似,只需要修改连接字符串。

public static DataTable GetDataTableFromExcel(string SourceFilePath)
{
    string ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
                                "Data Source=" + SourceFilePath + ";" +
                                "Extended Properties=Excel 8.0;";

    using (OleDbConnection cn = new OleDbConnection(ConnectionString))
    {
        cn.Open();

        DataTable dbSchema = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
        if (dbSchema == null || dbSchema.Rows.Count < 1)
        {
            throw new Exception("Error: Could not determine the name of the first worksheet.");
        }

        string WorkSheetName = dbSchema.Rows[0]["TABLE_NAME"].ToString();

        OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM [" + WorkSheetName + "]", cn);
        DataTable dt = new DataTable(WorkSheetName);

        da.Fill(dt);

        return dt;
    }
}

I am using csvReader from LumenWorks.Framework for uploading and importing the csv files into a sql table and a DataTable in memory which I create based on the columns imported. 我正在使用LumenWorks.Framework中的csvReader将csv文件上传和导入到sql表和内存中的DataTable,这是我根据导入的列创建的。

I also have the user map the fields in the ui and proceed to validate and prepare the data for import by labeling each record as insert/update/error. 我还让用户映射ui中的字段,并通过将每个记录标记为插入/更新/错误来继续验证和准备要导入的数据。 I then create/populate strongly typed DataSet for each table that will be affected and build the insert/update queries for Enterprise Library UpdateDataset() method. 然后,我为每个将受影响的表创建/填充强类型DataSet,并为Enterprise Library UpdateDataset()方法构建插入/更新查询。

Then I submit the transaction to insert/update the database. 然后我提交事务来插入/更新数据库。 -

The mapping is a grid with 4 columns. 映射是一个包含4列的网格。 ( import field name, destination table, destination field name, ignore, match status), with destination table and field names being selects which refresh based on table selected. (导入字段名称,目标表,目标字段名称,忽略,匹配状态),目标表和字段名称选择基于所选表的刷新。 I dynamically populate the selects. 我动态填充选择。 Initially select combo is populated with 1 value if the match is found, or please select if it isn't. 如果找到匹配,最初选择组合将填充1个值,或者如果不匹配则请选择。 ignore allows user to ignore the field. ignore允许用户忽略该字段。 match status is if a field was auto-mapped 匹配状态是指字段是否已自动映射

FileHelpers is your friend. FileHelpers是你的朋友。 I've used it happily for several projects and it has saved me much grief and labour 我愉快地用它来做几个项目,这给我带来了很多悲伤和劳动

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM