更新在datagridview中更改的Excel文件

时间:2018-08-28 11:20:05

标签: c# sql excel datagridview

我有一个通过OpenFileDialog()函数连接到任何Excel文件的应用程序,我想将所有更改保存到用户通过一个按钮“更新”在数据网格视图中进行的原始xls文件中。

应用图片: IMG

如您所见,有一个datagridview和按钮“ UPDATE”。 您可以看到上面的完整代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
using Accord.IO;
using Excel = Microsoft.Office.Interop.Excel;


namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {

        public static string path;
        public static string connStr;
        OleDbConnection conn = new OleDbConnection(connStr);
        OpenFileDialog opf = new OpenFileDialog();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            showbtn.Enabled = false;
            searchbtn.Enabled = false;
            searchaddbtn.Enabled = false;

        }

        private void openbtn_Click(object sender, EventArgs e)
        {
            opf.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm";
            if (opf.ShowDialog() == DialogResult.OK)
            {
                textBox3.Text = opf.FileName;
                path = opf.FileName;
            }
        }
        private void checkbtn_Click(object sender, EventArgs e)
        {
            try
            {
                if (conn != null && conn.State == ConnectionState.Closed)
                {
                    showbtn.Enabled = true;
                    Accord.IO.ExcelReader reader = new Accord.IO.ExcelReader(path);
                    string[] wsheets = reader.GetWorksheetList();
                    foreach (string worksheet in wsheets)
                    {
                        testcb.Items.Add(worksheet);

                    }
                    MessageBox.Show("Connected!");
                }
                else
                {
                    MessageBox.Show("Connection Failed");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void showbtn_Click(object sender, EventArgs e)
        {

                try
                {
                string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";
                OleDbConnection conn = new OleDbConnection(connStr);
                OleDbDataAdapter da = new OleDbDataAdapter("Select * from ["+ testcb.SelectedItem.ToString()+"$]", conn);
                    DataTable dt = new DataTable();
                    dataGridView2.DataSource = dt;
                    da.Fill(dt);                    
                    searchbtn.Enabled = true;
                    searchaddbtn.Enabled = true;
                comboBox1.Items.Clear();
                addcb.Items.Clear();
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    string temp2 = dt.Columns[i].ColumnName.ToString();
                    comboBox1.Items.Add(temp2.ToString());
                    addcb.Items.Add(temp2.ToString());
                }

            }
                catch (Exception ex)
                {

                    MessageBox.Show (ex.Message);
                }

        }

        private void searchbtn_Click(object sender, EventArgs e)
        {
            try
            {
                string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";
                OleDbConnection conn = new OleDbConnection(connStr);
                OleDbDataAdapter da = new OleDbDataAdapter("Select * from [" + testcb.SelectedItem.ToString() + "$] where [" + comboBox1.SelectedItem.ToString() + "] = '" + textBox5.Text + "'", conn);
                DataTable dt = new DataTable();
                da.Fill(dt);
                dataGridView2.DataSource = dt;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";
                OleDbConnection conn = new OleDbConnection(connStr);
                OleDbDataAdapter da = new OleDbDataAdapter("Select * from [" + testcb.SelectedItem.ToString() + "$] where [" + addcb.SelectedItem.ToString() + "] = '" + addtb.Text + "'", conn);
                DataTable ds = new DataTable();
                da.Fill(ds);
                DataTable combinedData = (DataTable)(dataGridView2.DataSource);
                combinedData.Merge(ds);
                dataGridView2.DataSource = combinedData;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void clearbtn_Click(object sender, EventArgs e)
        { 
            dataGridView2.DataSource = null;
        }

        private void nullbtn_Click(object sender, EventArgs e)
        {
            try
            {
                foreach (DataGridViewCell cell in dataGridView2.SelectedCells)
                {
                    dataGridView2.Rows[cell.RowIndex].Cells[cell.ColumnIndex].Value = 0;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error - " + ex);
            }

            }

        private void dataGridView2_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1) return;

            DataGridViewRow row = dataGridView2.Rows[e.RowIndex];
        }

        private void saveasbtn_Click(object sender, EventArgs e)
        {

            try
            {
                Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
                excel.Visible = true;
                Microsoft.Office.Interop.Excel.Workbook workbook = excel.Workbooks.Add(System.Reflection.Missing.Value);
                Microsoft.Office.Interop.Excel.Worksheet sheet1 = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets[1];
                int StartCol = 1;
                int StartRow = 1;
                int j = 0, i = 0;

                //Write Headers
                for (j = 0; j < dataGridView2.Columns.Count; j++)
                {
                    Microsoft.Office.Interop.Excel.Range myRange = (Microsoft.Office.Interop.Excel.Range)sheet1.Cells[StartRow, StartCol + j];
                    myRange.Value2 = dataGridView2.Columns[j].HeaderText;
                }

                StartRow++;

                //Write datagridview content
                for (i = 0; i < dataGridView2.Rows.Count; i++)
                {
                    for (j = 0; j < dataGridView2.Columns.Count; j++)
                    {
                        try
                        {
                            Microsoft.Office.Interop.Excel.Range myRange = (Microsoft.Office.Interop.Excel.Range)sheet1.Cells[StartRow + i, StartCol + j];
                            myRange.Value2 = dataGridView2[j, i].Value == null ? "" : dataGridView2[j, i].Value;

                        }
                        catch
                        {
                            ;
                        }
                    }
                }
                SaveFileDialog saveFileDialog1 = new SaveFileDialog();
                saveFileDialog1.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm";
                saveFileDialog1.Title = "Save an Excel file";
                saveFileDialog1.ShowDialog();


                if (saveFileDialog1.FileName != "")
                {

                    System.IO.FileStream fs = (System.IO.FileStream)saveFileDialog1.OpenFile();  //Save. The selected path can be got with saveFileDialog.FileName.ToString()
                    MessageBox.Show("Success");
                }
                else
                {
                    MessageBox.Show("Error");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void updatebtn_Click(object sender, EventArgs e)
        {

        }
    }
}

1 个答案:

答案 0 :(得分:0)

我建议看一下this帖子,其中描述了如何写入现有的Excel文件。