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!", "Prompt", 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 = "";

                   / / Table contents

                   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 < colCount)

                               strLine += ",";

                           If (dataGridView.Rows[j].Cells[k].Value == null)

                               strLine += "";

                           Else

                           {

                               String cell = dataGridView.Rows[j].Cells[k].Value.ToString().Trim();

                               / / Prevent it contains special symbols

                               Cell = cell.Replace("\"", "\"\"");

                               Cell = "\"" + cell + "\"";

                               strLine += cell;

                           }

                       }

                       sw.WriteLine(strLine);

                   }

                   sw.Close();

                   stream.Close();

                   MessageBox.Show("Data is exported to:" + saveFileDialog.FileName.ToString(), "Exported", MessageBoxButtons.OK, MessageBoxIcon.Information);

               }

               Catch (Exception ex)

               {

                   MessageBox.Show(ex.Message, "Export Error", MessageBoxButtons.OK, MessageBoxIcon.Information);

                   Return false;

               }

           }

           Return true;

       } 

2, C# will export the data in the DataGridView to Excel


Public static bool dataGridViewToExcel(DataGridView dataGridView)

        {

            If (dataGridView.Rows.Count == 0)

            {

                MessageBox.Show("No data to export!", "Prompt", 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 canceled

            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();

            If (xlApp == null)

            {

                MessageBox.Show("Unable to create Excel object, Excel may not be installed on your computer");

                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)workbook.Worksheets[1];//Get sheet1

                                                                                         //Write the title

            For (int i = 0; i < dataGridView.ColumnCount; i++)

            { worksheet.Cells[1, i + 1] = dataGridView.Columns[i].HeaderText; }

            / / Write the 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 saved successfully", "prompt", 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, the system will automatically create an Excel process, even if you use Excel.Quit (), it will not close. //* Parameters: Uniquely identify the process we created by the process ID, and then close the process Kill when closing Excel.Application. //* Return value: None ///Time: 2018-04-25 //******************************* ************************************************** *************// public static void Kill(Microsoft.Office.Interop.Excel.Application excel) { IntPtr 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.

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.