C# 我想在C语言中将对象[,]转换为双[,]#
我学习用C#阅读Excel 但我无法将对象[,]转换为双[,]C# 我想在C语言中将对象[,]转换为双[,]#,c#,C#,我学习用C#阅读Excel 但我无法将对象[,]转换为双[,] double[,] array; Excel.Application xlApp; Excel.Workbook xlWorkBook; Excel.Worksheet xlWorkSheet; object[,] temp; private void button1_Click(object sender, EventArgs e) { String path = "
double[,] array;
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object[,] temp;
private void button1_Click(object sender, EventArgs e)
{
String path = "C:\\Users\\Bob\\Desktop\\abcd.xlsx";
//Excel.Range range;
ReadExcelData(path);
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(path, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
GetTotalValue(xlWorkSheet);
}
在这段代码中,GetTotalValue(xlWorksheet)是getExcelValue
private object[,] GetTotalValue(Worksheet sheet)
{
Range usedRange = sheet.UsedRange;
Range lastCell = usedRange.SpecialCells(XlCellType.xlCellTypeLastCell);
MessageBox.Show(lastCell.Cells.Row.ToString());
MessageBox.Show(lastCell.Cells.Column.ToString());
Range totalRange = sheet.get_Range(sheet.get_Range("A1"), lastCell);
return (object[,])totalRange.get_Value();
}//end
我尝试了Array.Copy,但此方法是仅复制Array[]
所以我无法解决这个问题,因为double在内存中的大小可能与对象引用不同,因此数组的大小也会不同 C#没有很多多维数组的助手,LINQ在这里也不起作用。您必须自己转换它:
double[,] array = new double[temp.GetLength(0),temp.GetLength(1)];
for(int x = 0; x < array.GetLength(0); x++)
for(int y = y; y < array.GetLength(1); y++)
array[x,y] = (double)temp[x,y];
double[,]数组=新的double[temp.GetLength(0),temp.GetLength(1)];
for(int x=0;x
C#还提供了一个静态Array.ConvertAll方法,但它似乎缺少多维数组的重载
编辑:第二个必须是GetLength(1),而不是(0)。您也应该检查下限-Excel interop将返回基于1的数组。谢谢您的帮助