我在将值写入新的CSV文件时遇到了严重问题。
我收到一个csv文件,我从中解析所有值。这很好用,我把它带到了数据网格中。
我们要对此文件做的第一件事是重新安排它。就目前而言,有两组标题:一组沿着顶部,一组沿着左侧。基本上,我们反过来想要它:将左侧的标题放在顶部,顶部的标题按顺序放在文件中。
现在发生的事情是,以下代码使CSV具有一行(正确),具有正确的列数(而不是行,再次正确)...但是所有的值都是表是“1,1,1,1,1,1,1,1,1,1”等。
EG:
我得到的文件是这样的:
档案:,1,2,3,4,5
键入a,9%,10%,11%,12%,13%
b型,9%,10%,11%,12%,13%
c型,9%,10%,11%,12%,13%
类型d,9%,10%,11%,12%,13%
我想这样做:
文件:,输入a,输入b,输入c,输入d
1,9%,9%,9%,9%
2%,10%,10%,10%,10%
3%,11%,11%,11%,11%
4,12%,12%,12%,12%
5,13%,13%,13%,13%
这是我到目前为止的代码:
if (!File.Exists(path))
return null;
string full = Path.GetFullPath(path);
string file = Path.GetFileName(full);
string dir = Path.GetDirectoryName(full);
//create the "database" connection string
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=\"" + dir + "\\\";"
+ "Extended Properties=\"text;HDR=No;FMT=Delimited\"";
//create the database query
string query = "SELECT * FROM [" + file + "]";
//create a DataTable to hold the query results
DataTable dTable = new DataTable();
//create an OleDbDataAdapter to execute the query
OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, connString);
//Get the CSV file to change position.
try
{
//fill the DataTable
dAdapter.Fill(dTable);
string activedir = dir;
//Now write in new format.
StreamWriter sw = new StreamWriter(File.Create(dir + "\\modified_" + file.ToString()));
int iRowCount = dTable.Rows.Count;
foreach(DataRow dr in dTable.Rows)
{
string writeVal = (string)dTable.Columns[0].ToString();
sw.Write(writeVal);
sw.Write(",");
}
sw.Write(sw.NewLine);
sw.Close();
dAdapter.Dispose();
}
catch (InvalidOperationException /*e*/)
{ }
string newPath = dir + "\\modified_" + file.ToString();
if (!File.Exists(newPath))
return null;
string f = Path.GetFullPath(newPath);
string fi = Path.GetFileName(f);
string di = Path.GetDirectoryName(f);
//create the "database" connection string
string conn = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=\"" + di + "\\\";"
+ "Extended Properties=\"text;HDR=No;FMT=Delimited\"";
//create the database query
string q = "SELECT * FROM [" + fi + "]";
//create a DataTable to hold the query results
DataTable dTe = new DataTable();
//create an OleDbDataAdapter to execute the query
OleDbDataAdapter dA = new OleDbDataAdapter(q, connString);
//Get the CSV file to change position.
try
{
//fill the DataTable
dA.Fill(dTe);
}
catch (InvalidOperationException /*e*/)
{ }
return dTe;
任何帮助?
谢谢!
答案 0 :(得分:1)
更改文件以便 “string writeVal = ...”
现在是
对象writeVal = dr [0];
答案 1 :(得分:0)
我相信您正在寻找数据转置。 See this用于快速转置数据表。