Namespace:
Using system;
Using system. Collections. Generic;
Using system. LINQ;
Using system. Web;
Using system. Web. UI;
Using system. Web. UI. webcontrols;
Using Excel = Microsoft. Office. InterOP. Excel;
Using system. reflection;
Using system. Data. sqlclient;
Using system. Data;
The first method is to directly use two for loops to import data to excel.
For (int I; I)
{
For (Int J; j)
{
Excel1.cells [I, j] = datatable. Rows [I] [J]. tostring ();
}
}
This method is suitable for scenarios where the data volume is small and the number of columns is small.
The second method is to use a For Loop
Int colunt_num = datable. colunt. count;
For (int I; I)
{
Excel1.range [excel1.cells [I + 2, 1], excel1.cells [I + 2, column]. value = maid [I]. itemarray;
}
This method is similar to the first method.
The third method is to create a two-dimensional array in the memory, put the data in the two-dimensional array with two for loops, and then import the two-dimensional array into the table, which is very efficient.
// Obtain the number of rows and columns in the table
Int row_num = datatable. Rows. count;
Int column_num = datatable. Columns. count;
// Generate a two-dimensional array
Object [,] dataarry = new object [row_num, column_num];
// Put the data in the table into an array
For (INT I = 0; I <row_num; I ++)
{
For (Int J = 0; j <column_num; j ++)
{
Dataarry [I, j] = datatable. Rows [I] [J]. tostring ();
}
}
// Put the data in the array in Excel
Excel1.range [excel1.cells [1, 1], excel1.cells [row_num, column_num]. value = dataarry;
Three ways to import data from datatable to excel