简体   繁体   English

C#在Excel中打开CSV字符串而不保存字符串

[英]C# Opening csv string in Excel without saving the string

I have a string in csv format, that I wish to simply open in Excel, without first having to save the file. 我有一个csv格式的字符串,我希望直接在Excel中打开,而不必先保存文件。

Is this possible? 这可能吗? I've had a look at Interop but I cannot find the specific method that I need. 我看过Interop,但找不到所需的特定方法。

Thanks. 谢谢。

If you convert your csv-string to a 2-dimensional array first, you can pass it to a range of cells. 如果首先将csv字符串转换为二维数组,则可以将其传递到一系列单元格。

Excel.Range oRange = oSheet.Range("A1",Missing.Value);
oRange.Resize(myArray.GetLength(0),myArray.GetLength(1));
oRange.Value = myArray;

This code is written out of my mind, so I hope It's ok, but I think you get the picture. 这段代码是我脑子里写的,所以我希望没关系,但我认为您已经明白了。 If you like to include a header in your excel-file, just start the range from A2 instaed of A1. 如果您想在excel文件中包含标头,则只需从A1的A2位置开始即可。

Yes, just copy the values over manually. 是的,只需手动复制值即可。 You can find a sample here . 您可以在此处找到示例。

Adapting that sample to get a very short sample to get you started (please note, this sample is not complete and you need to read the complete sample to see how to do things properly): 修改该样本以获取一个非常简短的样本以帮助您入门(请注意,该样本尚未完成,您需要阅读完整的样本以了解如何正确执行操作):

Excel.Application oXL= new Excel.Application();
oXL.Visible = true;
Excel._Workbook oWB = (Excel._Workbook)(oXL.Workbooks.Add( Missing.Value ));
Excel._Worksheet oSheet = (Excel._Worksheet)oWB.ActiveSheet;
oSheet.Cells[1, 1] = [first value from csv];

But assuming that it's a range of values in the csv string, just do a String.Split on it and then use the array to populate a Range in the sheet, just check out the sample in the article for details. 但是假设它是csv字符串中的一个值范围,只需String.Split做一个String.Split ,然后使用数组填充工作表中的Range ,只需查看文章中的示例以了解详细信息即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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