C # export the data displayed in the dataGridView to Excel (ultra-simplified edition)

Source: Internet
Author: User

C # export the data displayed in the dataGridView to Excel (ultra-simplified edition)

Using System; using System. collections. generic; using System. linq; using System. text; using Microsoft. office. interop; using Microsoft. office. interop. excel; using System. windows. forms; using Excel = Microsoft. office. interop. excel; public class ExprotToExcel {public void DataToExcel (DataGridView dgv, ToolStripProgressBar tempProgressBar, ToolStripStatusLabel toolstrip) {if (dgv. rows. count = 0) {MessageBox. Show ("no data"); return;} MessageBox. show ("start generating data to be exported", "Export prompt", MessageBoxButtons. OK, MessageBoxIcon. information); Excel. application excel = new Excel. application (); excel. application. workbooks. add (true); excel. visible = false; for (int I = 0; I <dgv. columnCount; I ++) excel. cells [1, I + 1] = dgv. columns [I]. headerText; tempProgressBar. visible = true; tempProgressBar. minimum = 1; tempProgressBar. maxim Um = dgv. rowCount; tempProgressBar. step = 1; toolstrip. visible = true; for (int I = 0; I <dgv. rowCount; I ++) {for (int j = 0; j <dgv. columnCount; j ++) {if (dgv [j, I]. valueType = typeof (string) {excel. cells [I + 2, j + 1] = "'" + dgv [j, I]. value. toString ();} else {excel. cells [I + 2, j + 1] = dgv [j, I]. value. toString () ;}} toolstrip. text = "| status: the" + I + "/" + dgv is being generated. rowCount + ""; tempProgres SBar. Value = I + 1;} toolstrip. Text = "| status: generated successfully! "; MessageBox. Show (" generated successfully. Save it. "," Generate prompt ", MessageBoxButtons. OK, MessageBoxIcon. Information); excel. Visible = true ;}}

Related Article

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.