Three ways to import data from datatable to excel

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.