2014-01-05 69 views
0

我需要改變我的CSV文件的格式。如何重新格式化CSV文件?

我的CSV文件:

x,a,b,c 
e,,2,1 
f,3,15, 
g,7,8,9 

所需格式:

ea0 
eb2 
ec1 
fa3 
fb15 
fc0 
ga7 
gb8 
gc9 

我寫代碼,但它不工作:

string log = retval(textBox1.Text, 0, 512); 
string[,] head = new string[4, 4]; 

int row=0; 
int column=0; 

string[] lines = log.Split('\n'); 
foreach (string l in lines) 
{ 
    string[] split = l.Split(','); 
    foreach (string item in split) 
    { 

     head[row, column] = item; 
     column++; 
    } 
    row++; 
} 


for (row=1; row < 4; row++) 
{ 
    string tmp = ""; 
    for (column = 1; column < 4; column++) 
    { 
     tmp = head[row, column]; 

    } 
    listBox1.Items.Add(tmp); 
} 
+1

這種格式背後的邏輯是不是clear.Why你想要這個格式以及如何手動創建這種格式。 – Innovation

+0

你想要的「EA0」,「EB2」值'listBox1'就結了? –

+0

我正在爲他添加一個澄清編輯。請耐心等待。我破解了代碼! :) –

回答

0

我不是100%肯定你會在這裏的話,但這個怎麼樣:

foreach (string l in lines) 
{ 
    string[] split = l.Trim().Split(','); 
    foreach (string item in split) 
    { 

     head[row, column] = item; 
     column++; 
    } 
    row++; 
    column = 0; 
} 

for (row = 1; row < 4; row++) 
{ 
    for (column = 1; column < 4; column++) 
    { 
     string rowAndColumn = head[row, 0] + head[0, column]; 
     string value = string.IsNullOrEmpty(head[row, column]) ? "0" : head[row, column]; 

     listBox1.Items.Add(rowAndColumn + value); 
    } 
} 

一個重要的變化是在第一循環foreachcolumn = 0;。如果沒有這個,你的column索引總是會超出界限。

第二foreach環檢索的行和列值,並用數值串接它。這樣做,我會得到你想要的輸出。

+0

它運行良好,但在fc0這返回fc 請更正它 謝謝 –

+0

@HadiRanji它適用於我,但請參閱我的編輯。在這種情況下,我已切換線'串[]分裂= l.Split( ' ');''到串[]分裂= l.Trim()分割(',');'。這樣做應該可以防止線路在空白處結束的問題。 –

+0

對不起,我沒有看到它,非常感謝 –

0

你是從1開始的索引,而不是的0,

使用第是不是:

for (row=0; row < 4; row++) 
    { 
     string tmp = ""; 
     for (column = 0; column < 4; column++) 
     { 
      tmp = head[row, column]; 

     } 
     listBox1.Items.Add(tmp); 
    }