Sto cercando di leggere un file Excel in un elenco di Data.DataTable, anche se con il mio metodo corrente può richiedere molto tempo. Presto essenzialmente Foglio di lavoro per foglio di lavoro, cella per cella, e tende a richiedere molto tempo. C'è un modo più veloce per farlo? Ecco il mio codice:Importazione rapida di un DataTable in Excel
List<DataTable> List = new List<DataTable>();
// Counting sheets
for (int count = 1; count < WB.Worksheets.Count; ++count)
{
// Create a new DataTable for every Worksheet
DATA.DataTable DT = new DataTable();
WS = (EXCEL.Worksheet)WB.Worksheets.get_Item(count);
textBox1.Text = count.ToString();
// Get range of the worksheet
Range = WS.UsedRange;
// Create new Column in DataTable
for (cCnt = 1; cCnt <= Range.Columns.Count; cCnt++)
{
textBox3.Text = cCnt.ToString();
Column = new DataColumn();
Column.DataType = System.Type.GetType("System.String");
Column.ColumnName = cCnt.ToString();
DT.Columns.Add(Column);
// Create row for Data Table
for (rCnt = 0; rCnt <= Range.Rows.Count; rCnt++)
{
textBox2.Text = rCnt.ToString();
try
{
cellVal = (string)(Range.Cells[rCnt, cCnt] as EXCEL.Range).Value2;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException)
{
ConvertVal = (double)(Range.Cells[rCnt, cCnt] as EXCEL.Range).Value2;
cellVal = ConvertVal.ToString();
}
// Add to the DataTable
if (cCnt == 1)
{
Row = DT.NewRow();
Row[cCnt.ToString()] = cellVal;
DT.Rows.Add(Row);
}
else
{
Row = DT.Rows[rCnt];
Row[cCnt.ToString()] = cellVal;
}
}
}
// Add DT to the list. Then go to the next sheet in the Excel Workbook
List.Add(DT);
}
Purtroppo. – gustavodidomenico
"C'è un modo più veloce per farlo? Sfortunatamente no." Spazzatura assoluta. Questo codice crea (e erroneamente non riesce a disporre) un oggetto COM per ogni singolo valore di cella Excel in cui viene letto. Questo è il modo più lento possibile di farlo! È MOLTO più veloce leggere nell'intero foglio di lavoro in un array in un colpo solo, quindi scorrere gli elementi in quell'array. –