Problema com linhas e colunas de um CSV
Pergunta
Estou tendo um grande problema em escrever valores em um novo arquivo CSV.
Recebo um arquivo CSV do qual analiso todos os valores. Isso funciona bem, eu trouxe isso à tona e o coloquei em um DataGridView.
A primeira coisa que queremos fazer com esse arquivo é reorganizá-lo. Como está, existem dois conjuntos de cabeçalhos: um ao longo do topo e outro ao longo da esquerda. Basicamente, queremos o contrário: coloque os cabeçalhos à esquerda na parte superior e os cabeçalhos no topo para descer o arquivo.
O que acontece agora, porém, é que o código a seguir produz um CSV que tem uma linha (que é certa) com a quantidade correta de colunas (em vez de linhas, novamente corretas) ... no entanto, todos os valores da tabela são " 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 "etc.
POR EXEMPLO:
Eu recebo o arquivo assim:
Arquivo:, 1, 2, 3, 4, 5
tipo A, 9%, 10%, 11%, 12%, 13%
tipo B, 9%, 10%, 11%, 12%, 13%
tipo C, 9%, 10%, 11%, 12%, 13%
tipo D, 9%, 10%, 11%, 12%, 13%
Eu quero fazer assim:
Arquivo:, tipo A, tipo B, tipo C, tipo 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%
Aqui está o código que tenho até agora:
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;
Qualquer ajuda?
Obrigado!
Solução
Arquivo alterado para que "string writeVal = ..."
é agora
objeto writeVal = dr [0];
Outras dicas
Eu acredito que você está procurando transposição de dados. Veja isso para transposição rápida de um datatable.