简体   繁体   中英

How to AppendAllText in excel file for multi-variables in multi-columns using c#?

The following code line allows me to append the variable w1 in excel file. but appending process happens in the first column. how to make it for multi-variables {w1, w2, w3} in multi-columns?

File.AppendAllText(Path.Combine(docPath, "Groupbox1.CSV"), w1);

First, you're actually working with .CSV files, not Excel. The CSV stands for C omma S eparated V alues, so each value in a line of text on these files are typically separated by a comma (or other delimiters such as semicolon). The Excel application lets you open .CSV files, but they are different from Excel files which have either .xls or .xslx extensions. Excel will display values separated by commas in their own columns.

Then, say you have multiple variables. Then you can simply create one string with commas in between values, and write it to the file.

var w1 = "Data1";
var w2 = "Data2";
var w3 = "Data3";

// This creates a string, according to above data, that looks like
// "Data1,Data2,Data3"
var lineToWrite = string.Format("{0},{1},{2}", w1, w2, w3);
File.AppendAllText(Path.Combine(docPath, "Groupbox1.CSV"), lineToWrite);

Now we write that line to the file, and each data item is separated by a comma. Now when you open this with Excel, each data item will be displayed in its own column.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM