我有以下代码导入excel文档并解析它们,以便我可以在将数据保存到数据库之前对其进行操作。
我可以很好地解析.xlsx和.xls文件,但无法弄清楚如何将现有代码用于.csv文件
我工作的客户想要使用.csv文件类型来接受特殊字符。
OpenFileDialog opener = new OpenFileDialog();
opener.Filter = "Excel Files| *.xlsx;*.xls;*.csv;";
if (opener.ShowDialog() == DialogResult.Cancel)
return;
FileStream streamer = new FileStream(opener.FileName, FileMode.Open);
IExcelDataReader reader;
if (Path.GetExtension(opener.FileName) == ".xls")
{
reader = ExcelReaderFactory.CreateBinaryReader(streamer);
}
else if (Path.GetExtension(opener.FileName) == ".csv")
{
*** Need Something Here to read CSV Files that will work with
the rest of code***
}
else
{
reader = ExcelReaderFactory.CreateOpenXmlReader(streamer);
}
DataSet results = reader.AsDataSet();
results.Tables[0].Rows[0].Delete();
results.AcceptChanges();
foreach (System.Data.DataTable table in results.Tables)
{
foreach (DataRow dr in table.Rows)
{
>>> Do Something With the Data
}
}
答案 0 :(得分:0)
private void ReadCSVFile(string filepath)
{
//receiverList = new List<ReceiverUser>();
try
{
if (filepath == string.Empty)
return;
using (StreamReader sr = new StreamReader(FileUpload1.PostedFile.InputStream))
{
string line;
while ((line = sr.ReadLine()) != null)
{
SplitLine(line);
}
}
#region row add test
DataTable dt = new DataTable();
if (dt.Columns.Count == 0)
{
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Mail", typeof(string));
dt.Columns.Add("Amount", typeof(double));
}
DataRow NewRow;
/*
foreach (var item in receiverList)
{
NewRow = dt.NewRow();
NewRow[0] = item.Name + " " + item.Surname;
NewRow[1] = item.Mail;
NewRow[2] = item.Amount;
dt.Rows.Add(NewRow);
}
*/
grdRec.DataSource = dt;
grdRec.DataBind();
#endregion
}
catch (Exception)
{
}
}//end of function
此函数读取CSV文件,将参数加载到Datatable并将网格的数据源设置为Datatable。这是一个ASP.NET WebfoRM代码。
答案 1 :(得分:0)
假设你的IExcelDataReader
是第三方包,它读取Excel文件(一个非常安全的赌注)并且它本身不处理CSV(我不确定的部分),那么你总是可以处理CSV完全分开。
OLE有一个很好的CSV阅读器,所以这样的东西应该有效。
List<DataTable> tables = new List<DataTable>();
if (Path.GetExtension(opener.FileName) == ".csv")
{
OleDbConnection conn = new OleDbConnection(string.Format(
@"Provider=Microsoft.Jet.OleDb.4.0; Data Source={0};" +
"Extended Properties=\"Text;HDR=YES;FMT=Delimited\"",
opener.FileName
));
conn.Open();
string sql = string.Format("select * from [{0}]", Path.GetFileName(opener.FileName));
OleDbCommand cmd = new OleDbCommand(sql, conn);
OleDbDataReader reader = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader);
tables.Add(dt);
reader.Close();
}
else
{
FileStream streamer = new FileStream(opener.FileName, FileMode.Open);
IExcelDataReader reader = null;
if (Path.GetExtension(opener.FileName) == ".xls")
reader = ExcelReaderFactory.CreateBinaryReader(streamer);
else
reader = ExcelReaderFactory.CreateOpenXmlReader(streamer);
DataSet results = reader.AsDataSet();
results.Tables[0].Rows[0].Delete();
results.AcceptChanges();
foreach (DataTable table in results.Tables)
tables.Add(table);
}
然后只引用您的本地数据表列表(tables
)而不是Results.Tables,
,因为它现在已在本地范围内IExcelReader
。
foreach (System.Data.DataTable table in tables)
{
foreach (DataRow dr in table.Rows)
{
>>> Do Something With the Data
}
}
如果由于某种原因无法使用OLE,则.NET类库实际上具有CSV解析器。在我看来,它非常隐蔽,但很不错:
http://odedcoster.com/blog/2012/03/28/did-you-know-a-net-csv-parser-that-comes-with-visual-studio/
答案 2 :(得分:0)
您可以检查以下代码吗?这对您有用。
OpenFileDialog opener = new OpenFileDialog();
opener.Filter = "Excel Files| *.xlsx;*.xls;*.csv;";
if (opener.ShowDialog() == DialogResult.Cancel)
return;
FileStream streamer = new FileStream(opener.FileName, FileMode.Open);
IExcelDataReader reader;
if (Path.GetExtension(opener.FileName) == ".xls")
{
reader = ExcelReaderFactory.CreateBinaryReader(streamer);
}
else if (Path.GetExtension(opener.FileName) == ".csv")
{
var reader = ExcelReaderFactory.CreateReader(stream, new ExcelReaderConfiguration() {
// Gets or sets the encoding to use when the input XLS lacks a CodePage
// record, or when the input CSV lacks a BOM and does not parse as UTF8.
// Default: cp1252. (XLS BIFF2-5 and CSV only)
FallbackEncoding = Encoding.GetEncoding(1252),
// Gets or sets the password used to open password protected workbooks.
Password = "password",
// Gets or sets an array of CSV separator candidates. The reader
// autodetects which best fits the input data. Default: , ; TAB | #
// (CSV only)
AutodetectSeparators = new char[] { ',', ';', '\t', '|', '#' };
});
}
else
{
reader = ExcelReaderFactory.CreateOpenXmlReader(streamer);
}
DataSet results = reader.AsDataSet();
results.Tables[0].Rows[0].Delete();
results.AcceptChanges();
foreach (System.Data.DataTable table in results.Tables)
{
foreach (DataRow dr in table.Rows)
{
>>> Do Something With the Data
}
}
引用此链接 ExcelDataReader