我想插入String[][]
(二維數組)以代替「逐個單元格」或Row的excel。將二維數組插入到C#中的excel中WPF
另一件事: 我想打開一個模板XLS文件,寫入它並用另一個名稱保存它。 我試圖搜索谷歌已經2天了。
請幫我:-)
(在C#WPF)
我想插入String[][]
(二維數組)以代替「逐個單元格」或Row的excel。將二維數組插入到C#中的excel中WPF
另一件事: 我想打開一個模板XLS文件,寫入它並用另一個名稱保存它。 我試圖搜索谷歌已經2天了。
請幫我:-)
(在C#WPF)
我正在使用對象終於沒有[,],並插入RO通過
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(ExcelFile);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
Excel.Range firstCell = xlWorkSheet.get_Range("A1", Type.Missing);
Excel.Range lastCell = xlWorkSheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
Excel.Range worksheetCells = xlWorkSheet.get_Range(firstCell, lastCell);
int rowCount = worksheetCells.Rows.Count;
int colCount = worksheetCells.Columns.Count;
object[,] cellFormulas = new String[rowCount, colCount];
cellFormulas = worksheetCells.Formula as object[,];
// String[][] ResultMatrix = new String[rowCount][];
xlWorkBook.Close(true, misValue, misValue);
xlApp.Workbooks.Close();'
我能解決的第一個問題是:
我要插入的String [] [](二維數組)來改爲「逐個細胞」或Row。
在第一你應該String[][]
轉換爲String[,]
,然後使用這個(我測試):
public static void ExportToExcel(String[,] data, String sheetName, String path)
{
var dt = new DataTable();
for (var row = 0; row < data.GetLength(0); ++row)
{
for (var col = 0; col < data.GetLength(1); col++)
{
dt.Rows[row][col] = data[row, col];
}
}
Excel.Application oXL;
Excel.Workbook oWB;
Excel.Worksheet oSheet;
//Excel.Range oRange;
oXL = new Excel.Application();
oXL.Visible = true;
oXL.DisplayAlerts = false;
oWB = oXL.Workbooks.Add(Missing.Value);
oSheet = (Excel.Worksheet)oWB.ActiveSheet;
oSheet.Name = sheetName;
var rowCount = 1;
foreach (DataRow dr in dt.Rows)
{
rowCount += 1;
for (var i = 1; i < dt.Columns.Count + 1; i++)
{
if (rowCount == 2)
{
oSheet.Cells[1, i] = dt.Columns[i - 1].ColumnName;
}
oSheet.Cells[rowCount, i] = dr[i - 1].ToString();
}
}
oSheet = null;
oWB.SaveAs(path, Excel.XlFileFormat.xlWorkbookNormal,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Excel.XlSaveAsAccessMode.xlExclusive,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value);
oWB.Close(Missing.Value, Missing.Value, Missing.Value);
oWB = null;
oXL.Quit();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
注:應使用在你引用添加的Microsoft.Office.Interop.Excel。
你想要的東西,如:
雖然我認爲它只會在交錯數組,而不是二維數組。未在2d陣列上測試。
var startCell = Worksheet.Cells[row, col];
var endCell = Worksheet.Cells[row, col];
var writeRange = (Excel.Range)Worksheet.Cells[startCell, endCell];
writeRange.Value = myArray;
排他並不想通過細胞做這個細胞。 –