获取CSV导入数据库
public class CSVHelper {
/// <summary>
/// 获取CSV导入的数据
/// </summary>
/// <param name="filePath">文件路径</param>
/// <param name="fileName">文件名称(.csv不用加)</param>
/// <returns></returns>
public static DataTable GetCsvData(string filePath, string fileName) {
string path = Path.Combine(filePath, fileName + ".csv");
string connString = @"Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" + filePath + ";Extensions=asc,csv,tab,txt;";
try {
using (OdbcConnection odbcConn = new OdbcConnection(connString)) {
odbcConn.Open();
OdbcCommand oleComm = new OdbcCommand();
oleComm.Connection = odbcConn;
oleComm.CommandText = "select * from [" + fileName + "#csv]";
OdbcDataAdapter adapter = new OdbcDataAdapter(oleComm);
DataSet ds = new DataSet();
adapter.Fill(ds, fileName);
odbcConn.Close();
if (File.Exists(path)) {
File.Delete(path);
}
return ds.Tables[0];
}
} catch (Exception ex) {
if (File.Exists(path)) {
File.Delete(path);
}
throw ex;
}
}
public static void DataTableToCSV(DataTable table, string file) {
string title = "";
FileStream fs = new FileStream(file, FileMode.Create);
StreamWriter sw = new StreamWriter(new BufferedStream(fs), System.Text.Encoding.Default);
for (int i = 0; i < table.Columns.Count; i++) {
title += table.Columns[i].ColumnName + ",";
}
title = title.Substring(0, title.Length - 1) + "\n";
sw.Write(title);
foreach (DataRow row in table.Rows) {
string line = "";
for (int i = 0; i < table.Columns.Count; i++) {
line += row[i].ToString() + ",";
}
line = line.Substring(0, line.Length - 1) + "\n";
sw.Write(line);
}
sw.Close();
fs.Close();
}
}