How to Improve the Performance of importing data to excel in C #

Source: Internet
Author: User

C # importing table data into Excel usually inserts data into Excel one by one cell. As follows (onlyCodeSegment ):

...

Object missing = missing. value;

Excel. Application myexcel = new excel. Application (); // create an Excel instance

Myexcel. application. workbooks. open (filename, missing, and missing); // open the filename table

Myexcel. Visible = false;

Excel. Workbook myworkbook = myexcel. workbooks [1];

Excel. worksheet myworksheet = (Excel. worksheet) myexcel. worksheets [1]; // declare a page of instances

...

For (INT I = 0; I <rownum; I ++)

{

Gridviewrow gvr = mydata. Rows [I];

For (Int J = 0; j <colnum; j ++)

{

Myexcel. cells [I + 8, J + 1] = "'" + gvr. cells [J]. Text. Replace ("& nbsp ;","");

}

}

...

However, the efficiency of cell assignment to excel is very low (because every time a cell value is assigned back, an Excel COM + component interface is called). If there is more data, access to the Excel COM + component is frequent, resulting inProgramThe operation efficiency is extremely low.

To solve this problem, we need to reduce the number of cell visits. According to the Excel API, you can assign a value (array) to its attribute value2 to achieve the same effect as the above Code. This avoids the sharp reduction in performance caused by frequent cell access.

The improved code is as follows:

...

Array arr = array. createinstance (typeof (string), rownum, colnum );

For (I = 0; I <rownum; I ++)

{

For (j = 0; j <colnum; j ++)

{

Arr. setvalue (mydata. Rows [I]. cells [J]. Text. Replace ("& nbsp", ""), I, j );

}

}

Excel. Range = myworksheet. get_range (myworksheet. cells [5, 1], myworksheet. cells [rownum + 4, colnum]);

Range. value2 = arr;

...

BTW: I always think that the name of the Excel attribute value2 looks uncomfortable, but it is not very standard. I wonder why they should name it like this.

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.