我在我的程序中有一些字符串變量,我需要把它放到CSV文件中。例如c#格式化CSV
。
var1 = "abc";
var2 = "bbb";
var3 = "
-vvv
-xxx
-zzz
-ccc
-ddd
"; // Var 3 is a multiline string, need it to be put in one cell
CSV文件:
Col1 Col2 Col3 (1 cell)
abc bbb -vvv
-xxx
-zzz
-ccc
-ddd
然後在下一行: VAR1(的newval)VAR2(的newval)VAR3(的newval)
的問題是如何甲酸鹽CSV文件變種X雲以colx等等。
我的代碼如下所示:
string getDir = Directory.GetCurrentDirectory();
DirectoryInfo d = new DirectoryInfo(@getDir + "\\src");
FileInfo[] Files = d.GetFiles("*.txt");
string str = "";
foreach(FileInfo file in Files)
{
str = str + "," + file.Name;
}
string lines="col1," + "col2," + "col3," + "col4 ," + "col5," + "col6," + "\n";
int ncheck = 1;
int countFiles = d.GetFiles().Length;
int vcheck = 0;
while (ncheck <= /*countFiles*/1)
{
var getfile = str.Split(',')[ncheck];
lines = lines + getfile;
while (vcheck <= 4)
{
string startSTR = "a1,a2,a3,a4,a5";
var starts = startSTR.Split(',')[vcheck];
string endSTR = "b1,b2,b3,b4,b5";
var ends = endSTR.Split(',')[vcheck];
string St = System.IO.File.ReadAllText(d + "\\" + getfile);
int pFrom = St.IndexOf(starts) + starts.Length;
if (St.IndexOf(starts) == -1 || St.IndexOf(ends) == -1) {pFrom=0;};
int pTo = St.LastIndexOf(ends);
if (St.IndexOf(starts) == -1 || St.IndexOf(ends) == -1) {pTo=pFrom+0;};
String result = St.Substring(pFrom, pTo - pFrom);
if (St.IndexOf(starts) == -1 || St.IndexOf(ends) == -1) {result="Not found";};
/*Console.WriteLine(starts);
Console.WriteLine(result);
Console.WriteLine(ends);*/
Console.WriteLine(lines);
lines = lines + "," + result;
Console.WriteLine(lines);
vcheck++;
}
lines = lines + "\n";
ncheck++;
vcheck=0;
}
System.IO.StreamWriter filetxt = new System.IO.StreamWriter(@getDir + "\\test.csv");
filetxt.WriteLine(lines);
filetxt.Close();
它正在爲txt文件,然後進行字符串搜索src目錄,最後保存到CSV文件。正如我之前所說的,由於一個字符串有多行需要在一個單元格中,所以我在格式化文檔時遇到了問題。
有沒有更好的方法來解決這個問題?
那麼問題是什麼? – CalC
請發佈您迄今爲止編寫CSV文件的代碼 –
到目前爲止我只使用分隔符,但有沒有更好的方法通過c#在選定的單元格中放置一些var? – michal