2017-05-05 50 views
0

我试图将Excel工作表读入数组,但是当我读出数组时,整行的所有值都保存在由';'分隔的第一列中。Interop Excel将所有值读入1行

如何将它们妥善保存在二维数组中?

这是我的代码:

using Microsoft.Office.Interop.Excel; 
using System; 
using System.IO; 

namespace BB_Entwurf_2 
{ 
class Program 
{ 
    public static void Main(string[] args) 
    { 
     ApplicationClass app = new ApplicationClass(); 
     Workbook book = null; 
     Worksheet sheet = null; 

     string currentDir = Environment.CurrentDirectory; 
     string excelPath; 
     excelPath = Path.Combine(currentDir, "MyFile.csv"); 

     app.Visible = false; 
     app.ScreenUpdating = false; 
     app.DisplayAlerts = false; 

     book = app.Workbooks.Open(excelPath); 

     sheet = (Worksheet)book.Worksheets[1]; 

     int rowCount = sheet.UsedRange.Rows.Count; 

     Console.WriteLine(rowCount); 

     Range range = sheet.UsedRange; 

     object[,] myExcelFileValues = (object[,])range.Value2; 

     range = null; 

     string test = (Convert.ToString(myExcelFileValues[1,1])); 

     Console.WriteLine(test); 

     test = (Convert.ToString(myExcelFileValues[2,2])); 

     Console.WriteLine(test); 

     System.Runtime.InteropServices.Marshal.FinalReleaseComObject(sheet); 
     sheet = null; 
     book.Close(false); 
     System.Runtime.InteropServices.Marshal.FinalReleaseComObject(book); 
     book = null; 
     app.Quit(); 
     System.Runtime.InteropServices.Marshal.FinalReleaseComObject(app); 
     app = null; 

     Console.Write("Press any key to continue . . . "); 
     Console.ReadKey(true); 
    } 
} 
} 
+1

使用Excel这样的处理CSV文件会导致你头疼的问题。为什么不使用专用的CSV解析器? – Equalsk

+0

可悲的是,我现在工作,我不能安装任何东西,只能与我有。因此,生病不得不以某种方式使用Excel。 –

+0

所以使用Excel不是_“安装任何东西”_? – MickyD

回答

0

我会同意有关CSV解析器的注释,但如果您在使用Excel时无法设置,则它不会自动在您的分号上分隔。您需要首先对列执行文本。喜欢的东西:

range.TextToColumns(range[1, 1], XlTextParsingType.xlDelimited, XlTextQualifier.xlTextQualifierDoubleQuote, Semicolon: true); 

如果大多数/所有的值是字符串,你可以只在split你的C#。

前述“CSV分析器”的解决办法只是:

excelPath = Path.Combine(currentDir, "MyFile.csv"); 
string[] lines = File.ReadAllLines(excelPath); 
List<string[]> values = new List<string[]>(); 
foreach (string line in lines) 
{ 
    values.Add(line.Split(';')); 
} 
// parse strings into int, double, date, etc. 

其实代码少,没有必需的设备...

0

你可以把第一个空白阵列,并采取一个循环接一个得到的值作为一个跟随

string[] arr = new string[]; 
Excel.Application application = new Excel.Application(); 
Excel.Workbook workbook = application.Workbooks.Open(path); 
Excel.Worksheet worksheet = workbook.ActiveSheet; 
Excel.Range range = worksheet.UsedRange;     
    for (int row = 1; row <= range.Rows.Count; row++) 
{ 
    arr[row-1] = ((Excel.Range)range.Cells[row, 1]).Text; 
}