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 ;}}