2

我想使用 C# asp.net 4.0 将.csv文件数据导入和导出到 sql server 2008/2012。

4

2 回答 2

0
/*
 * Loads the csv file into a DataSet.
 * 
 * If the numberOfRows parameter is -1, it loads all rows, otherwise it
 * loads the first specified number of rows (for preview)
 */

public DataSet LoadCSV(int numberOfRows)
{
    DataSet ds = new DataSet();
    try
    {
        // Creates and opens an ODBC connection
        string strConnString = "Driver={Microsoft Text Driver (*.txt; *.csv)};
            Dbq=" + this.dirCSV.Trim() + ";
            Extensions=asc,csv,tab,txt;Persist Security Info=False";
        string sql_select;
        OdbcConnection conn;
        conn = new OdbcConnection(strConnString.Trim());
        conn.Open();

        //Creates the select command text
        if (numberOfRows == -1)
        {
            sql_select = "select * from [" + 
                    this.FileNevCSV.Trim() + "]";
        }
        else
        {
            sql_select = "select top " + numberOfRows + 
                " * from [" + this.FileNevCSV.Trim() + "]";
        }

        //Creates the data adapter
        OdbcDataAdapter obj_oledb_da = new OdbcDataAdapter(sql_select, conn);

        //Fills dataset with the records from CSV file
        obj_oledb_da.Fill(ds, "csv");

        //closes the connection
        conn.Close();
    }
    catch (Exception e) //Error
    {
        MessageBox.Show(e.Message, "Error - LoadCSV",
                MessageBoxButtons.OK,MessageBoxIcon.Error);
    }
    return ds;
}
于 2013-10-24T10:21:09.460 回答
0

嗨,考虑到您想将文件导出datatable.csv文件,您可以这样做:

var lines = new List<string>();

string[] columnNames = dataTable.Columns.Cast<datacolumn>().
                                  Select(column => column.ColumnName).
                                  ToArray();

var header = string.Join(",", columnNames);
lines.Add(header);

var valueLines = dt.AsEnumerable()
                   .Select(row => string.Join(",", row.ItemArray));            
lines.AddRange(valueLines );

File.WriteAllLines("excel.csv",lines);

对于将.csv文件导入sql这里是一个片段代码,.csv首先读取文件然后将其写入 adatatable然后您可以使用您喜欢的任何技术将该数据表保存到 sqlserver(ado.net , linqtosql , entityframework , etc)

using (CachedCsvReader csv = new CachedCsvReader(new StreamReader(filePath), true))
{
    DataTable Table = new DataTable();
    Table.Load(csv);
}

查看这些链接也可能很有用:

http://www.codeproject.com/Articles/30705/C-CSV-Import-Export
http://www.codeproject.com/Articles/9258/A-Fast-CSV-Reader
http://dotnetawesome.blogspot.com/2013/11/how-to-import-export-database-data-from.html
于 2013-10-24T08:06:46.990 回答