这个是上传.CSV文件后将数据转为DataTable.希望对你有所帮助!
var file = Request.Files["Brower..."];
var str = Path.GetTempFileName() + Path.GetExtension(file.FileName);
file.SaveAs(str);
DataTable tbcsv = ReadFromCsv(str, UTF8Encoding.UTF8, ',');
public static DataTable ReadFromCsv(string fileName, Encoding encoding, char separator)
{
DataTable table = null;
if (fileName != null && !fileName.Equals(string.Empty))
{
try
{
// If required, you can collect some useful info from the file
FileInfo info = new FileInfo(fileName);
string tableName = info.Name;
// Prepare for the data to be processed into a DataTable
// We don't know how many records there are in the .csv, so we
// use a List<string> to store the records in it temporarily.
// We also prepare a DataTable;
List<string> rows = new List<string>();
// Then we read in the raw data
StreamReader reader = new StreamReader(fileName, encoding);
string record = reader.ReadLine();
while (record != null)
{
if (record.IndexOf("Keyword") != -1)
{
break;
}
record = reader.ReadLine();
}
while (record != null)
{
rows.Add(record);
record = reader.ReadLine();
}
// And we split it into chuncks.
// Note that we keep track of the number of columns
// in case the file has been tampered with, or has been made
// in a weird kind of way (believe me: this does happen)
// Here we will store the converted rows
List<string[]> rowObjects = new List<string[]>();
int maxColsCount = 0;
for (int i = 0; i < rows.Count; i++)
{
string s = rows[i].ToString();
string[] convertedRow = s.Split(new char[] { separator });
if (convertedRow.Length > maxColsCount)
maxColsCount = convertedRow.Length;
rowObjects.Add(convertedRow);
}
//foreach ( string s in rows ) {
// string [] convertedRow = s.Split ( new char [] { separator } );
// if ( convertedRow.Length > maxColsCount )
// maxColsCount = convertedRow.Length;
// rowObjects.Add ( convertedRow );
//}
// Then we build the table
table = new DataTable(tableName);
for (int i = 0; i < rowObjects[0].Length; i++)
{
// Change this if you want other datatypes
// make sure you also convert the string[] to
// the corect datataype
try
{
table.Columns.Add(new DataColumn(rowObjects[0][i]));
}
catch
{
break;
}
}
foreach (string[] rowArray in rowObjects)
{
try
{
table.Rows.Add(rowArray);
}
catch
{
continue;
}
}
table.Rows.RemoveAt(0);
table.AcceptChanges();
}
catch
{
throw new Exception("Error in ReadFromCsv: IO error.");
}
}
else
{
throw new FileNotFoundException("Error in ReadFromCsv: the file path could not be found.");
}
return table;
}
给一个例子:CSV 文件分析与导入数据库
http://blog.csdn.net/greenery/archive/2008/08/28/2843773.aspx
C#中读取文本文件导入SQL数据库解决方法
http://alligator.blog.51cto.com/36993/102446
还可以通过使用BULK INSERT
用法如下:
stu.csv 结构
1,Jim
2,Kate
3,Tom
...
BULK INSERT dbo.TABLE1
FROM 'd:\stu.csv'
WITH (
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)
查看table1里的数据
select * from table1
就ok了。