C # import data from DataGridView into a CSV file and export to Excel

Source: Internet
Author: User
1. Import data from DataGridView into a CSV file

 public static bool Datagridviewtocsv (DataGridView DataGridView) {if (DataGridView.Rows.Count = = 0)                {MessageBox.Show ("No data to export!", "hint", MessageBoxButtons.OK, MessageBoxIcon.Information);            return false;            } SaveFileDialog SaveFileDialog = new SaveFileDialog ();            Savefiledialog.filter = "CSV files (*.csv) |*.csv";            Savefiledialog.filterindex = 0;            Savefiledialog.restoredirectory = true;            Savefiledialog.createprompt = true;            Savefiledialog.filename = null;            Savefiledialog.title = "Save";                 if (savefiledialog.showdialog () = = DialogResult.OK) {Stream stream = Savefiledialog.openfile ();                StreamWriter SW = new StreamWriter (Stream, System.Text.Encoding.GetEncoding (-0));                String strLine = ""; try {//header for (int i = 0; i < DATAGRIdview.columncount;                        i++) {if (i > 0) strLine + = ","; StrLine + = Datagridview.columns[i].                    HeaderText;                    } strline.remove (strline.length-1); Sw.                    WriteLine (StrLine);                    StrLine = "";                        The contents of the table for (int j = 0; J < DataGridView.Rows.Count; J + +) {                        StrLine = "";                        int colcount = DataGridView.Columns.Count; for (int k = 0; k < ColCount; k++) {if (k > 0 && K < c                            Olcount) StrLine + = ","; if (Datagridview.rows[j]. CELLS[K].                            Value = = null) StrLine + = ""; else {string cell = DaTAGRIDVIEW.ROWS[J]. CELLS[K]. Value.tostring ().                                Trim (); Prevent the inside containing the special symbol cell = cell.                                Replace ("\" "," \ "\") ";                                Cell = "\" "+ cell +" \ ";                            StrLine + = cell; }} SW.                    WriteLine (StrLine); } SW.                    Close (); Stream.                    Close (); MessageBox.Show ("Data is exported to:" + saveFileDialog.FileName.ToString (), "Export Complete", MessageBoxButtons.OK,                MessageBoxIcon.Information); } catch (Exception ex) {MessageBox.Show (ex.                    Message, "Export error", MessageBoxButtons.OK, MessageBoxIcon.Information);                return false;        }} return true; }

public static bool Datagridviewtoexcel (DataGridView DataGridView) {if (DataGridView.Rows.Count = = 0)                {MessageBox.Show ("No data to export!", "hint", MessageBoxButtons.OK, MessageBoxIcon.Information);            return false;            } String fileName = "";            String savefilename = "";            SaveFileDialog Savedialog = new SaveFileDialog ();            Savedialog.defaultext = "xlsx";            Savedialog.filter = "Excel file |*.xlsx";            Savedialog.filename = FileName;            Savedialog.showdialog ();            Savefilename = Savedialog.filename; if (Savefilename.indexof (":") < 0) return false;            was ordered to cancel Microsoft.Office.Interop.Excel.Application xlapp = new Microsoft.Office.Interop.Excel.Application ();                if (xlapp = = null) {MessageBox.Show ("Cannot create Excel object, your computer may not have Excel installed");            return false; } Microsoft.Office.IntErop.            Excel.Workbooks Workbooks = xlapp.workbooks; Microsoft.Office.Interop.Excel.Workbook Workbook = workbooks.            ADD (Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet); Microsoft.Office.Interop.Excel.Worksheet Worksheet = (Microsoft.Office.Interop.Excel.Worksheet) work Book.                         worksheets[1];//get Sheet1//write title for (int i = 0; i < Datagridview.columncount; i++) {worksheet. Cells[1, i + 1] = Datagridview.columns[i]. HeaderText;  }//write value for (int r = 0; r < DataGridView.Rows.Count; r++) {for (int i = 0; i < Datagridview.columncount; i++) {worksheet. Cells[r + 2, i + 1] = Datagridview.rows[r]. Cells[i].                Value;            } System.Windows.Forms.Application.DoEvents (); } woRksheet.            Columns.EntireColumn.AutoFit ();//Column width Adaptive MessageBox.Show (fileName + "Data Save succeeded", "hint", MessageBoxButtons.OK); if (savefilename! = "") {try {workbook.                    Saved = true; Workbook.  SaveCopyAs (Savefilename);                                 Filesaved = true;                                          } catch (Exception ex) {//filesaved = false; MessageBox.Show ("An error occurred while exporting the file, the file may be being opened!") \ n "+ ex.                Message);            }} xlapp.quit ();            Kill (xlapp); Gc.        Collect ();//forcibly Destroy return true; }
//************************************************************************        * Function: When using the Excel.Application method, an Excel process is created automatically, even if you use Excel.quit (), it will not be closed.        * Parameters: The process ID uniquely identifies the process that we created, and then kill the process together when the Excel.Application is closed. * Return value: No//* time: 2018-04-25//******************************************************************************** public static void Kill (Microsoft.Office.Interop.Excel.Application Excel) {INTP TR t = new IntPtr (Excel.            Hwnd);            int k = 0;            GetWindowThreadProcessId (t, out K);            System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById (k);        P.kill (); }
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.

Tags Index: