我在我的程序中有一些字符串变量,我需要把它放到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