winforms 如何从List C#导出Excel< string>?

9gm1akwq  于 2023-03-31  发布在  C#
关注(0)|答案(1)|浏览(135)

我有一个列表,内容看起来像这样

"Food"<|||>"Candy"<|||>"15"
"System"<|||>"IOS, Android"<|||>"2023"
"Fruit"<|||>"Apple,Orange "<|||>"100"
"Wine"<|||>"Whisky"<|||>"250"

我尝试特定的字符<|||>,这将是定义分离到excel格式。excel结果将有3列。

但我不知道它可以做,这看起来很困难,因为excel只会识别逗号,不确定它是否可以使用特殊字符,在单元格内容中,我们也有逗号。

var lines = new List<string>();
lines.AddRange("Food"<|||>"Candy"<|||>"15","System"<|||>"IOS, Android"<|||>"2023","Fruit"<|||>"Apple,Orange "<|||>"100","Wine"<|||>"Whisky"<|||>"250");
//export to excel
biswetbf

biswetbf1#

由于excel文件的最后一列包含一个整数,因此您可以使用条件结构来检查当前索引处的数组成员是否包含一个数字,使用Int32.TryParse(),然后将该项目和换行符追加到csv中,否则将该项目和逗号追加,如下面的代码所示。

var array = new string[]
{
    "Food","Candy","15",
    "System","IOS, Android","2023",
    "Fruit","Apple, Orange","100",
    "Wine","Whisky","250"
};
//create a new list to hold the items
var myList = new List<string>();
//copy the items from the array to the list
myList.AddRange(array);
//create the csv file if it does not exist
if (!File.Exists("items.csv"))
{
    File.Create("items.csv");
}
//open the file with a stream writer for editing
using (var streamWriter = new StreamWriter("items.csv"))
{
    foreach (var item in myList)
    {
        if (Int32.TryParse(item, out var res))
        {
            //append the item to the file and a line break
            streamWriter.Write(item+"\n");
        }
        else
        {
            //replace the comma in the current string with space
            var str = item.Replace(",", " ");
            //append the item and a comma
            streamWriter.Write(str+",");
        }
    }
}

检查以下文件item.csv的excel输出。

相关问题