我正在創建一個讀取製表符分隔文本文件的小應用程序,進行一些更改,然後創建一個Excel 2007 .xlsx文件。我在計算如何從字符串數組中取出行並將它們寫入Excel文件時遇到了困難,使用選項卡將行分成列。我希望這是有道理的。如何使用製表符分隔符將字符串數組寫入Excel文件?
我有string Lines[]
包含這樣的事情:
Item1\tItem2\tItem3\tItem4
ItemA\tItemB\tItemC\tItemD
Item5\tItem6\tItem7\tItem8
我想創建一個看起來像這樣的Excel文件:
A B C D
Item1 Item2 Item3 Item4
ItemA ItemB ItemC ItemD
Item5 Item6 Item7 Item8
我嘗試以下,但它只是放第一行從Lines[]
分成每一行,並且不分隔成列:
string Lines[] = GetLines();
Excel.Application xlApp;
Excel.Workbook xlWb;
Excel.Worksheet xlWs;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlWb = xlApp.Workbooks.Add(misValue);
xlWs = (Excel.Worksheet)xlWb.Worksheets.get_Item(1);
Excel.Range c1 = (Excel.Range)xlWs.Cells[2, 1];
Excel.Range c2 = (Excel.Range)xlWs.Cells[2 + lines.Length, 1];
Excel.Range range = xlWs.get_Range(c1, c2);
range.Value = lines;
range.TextToColumns(
range,
Microsoft.Office.Interop.Excel.XlTextParsingType.xlDelimited,
Microsoft.Office.Interop.Excel.XlTextQualifier.xlTextQualifierNone,
false,
true // This is flag to say it is tab delimited
);
xlApp.Visible = true;
任何意見將不勝感激!謝謝!
這裏是目前我得到的輸出:
A B C D
Item1\tItem2\tItem3\tItem4
Item1\tItem2\tItem3\tItem4
Item1\tItem2\tItem3\tItem4
編輯:我已經更新了我的代碼以@ jiverson的建議,現在該行分成列在Excel,而是從Lines[]
第一線仍然出現在Excel的每一行中。爲什麼?
編輯#2:下面是更新工作代碼:
Excel.Application xlApp;
Excel.Workbook xlWb;
Excel.Worksheet xlWs;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlWb = xlApp.Workbooks.Add(misValue);
xlWs = (Excel.Worksheet)xlWb.Worksheets.get_Item(1);
int currentRow = 2;
string[] lines = GetLines();
for (int i = 0; i < lines.Length; i++)
{
string line = lines[i]; //get the current line
string[] values = line.Split('\t'); //split the line at the tabs
//
// .. i do some things to specific values here ..
//
lines[i] = String.Join("\t", values); //put the updated line back together
Excel.Range currentRange = (Excel.Range)xlWs.Cells[currentRow, 1]; //get the next row
currentRange.Value = lines[i]; //write the line to Excel
currentRow++;
}
Excel.Range c1 = (Excel.Range)xlWs.Cells[2, 1]; //get the first cell
Excel.Range c2 = (Excel.Range)xlWs.Cells[2 + lines.Length, 1]; //get the last cell
Excel.Range range = xlWs.get_Range(c1, c2); //set the range as the used area
range.TextToColumns(//split the row into columns
range,
Excel.XlTextParsingType.xlDelimited,
Excel.XlTextQualifier.xlTextQualifierNone,
false,
true // This is flag to say it is tab delimited
);
使用''\ t''分割字符串並將每個值寫入每個對應的單元格 – chancea