在datagrid veiw中更新Excel文件并保存到数据库

时间:2018-07-18 05:58:04

标签: c# excel datagridview import

我想从excel导入将数据更新到datagridview的帮助。 我可以成功导入数据,并且datagrid已绑定到数据库表。但我似乎找不到任何方法将已导入的Excel工作表保存到数据库,然后用另一个Excel导入对其进行更新。我也希望您对我如何使应用程序轻量化,以使其不会滞后于大量数据提出建议

using ExcelDataReader;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Voluntary_Dtabase
{

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void toolStripButton1_Click(object sender, EventArgs e)
    {

    }

    private void Form1_Load(object sender, EventArgs e)
    {
        // TODO: This line of code loads data into the 'dbvoluntaryDataSet.iexel' table. You can move, or remove it, as needed.


    }
    DataSet result;
    private void btnImport_Click(object sender, EventArgs e)
    {
        using(OpenFileDialog ofd = new OpenFileDialog() { Filter="Excel Workbook|*.xlsx", ValidateNames = true })
        {
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    FileStream fs = File.Open(ofd.FileName, FileMode.Open, FileAccess.ReadWrite);
                    IExcelDataReader reader = ExcelReaderFactory.CreateReader(fs);
                    result = reader.AsDataSet(new ExcelDataSetConfiguration()
                    {
                        ConfigureDataTable = (data) => new ExcelDataTableConfiguration()
                        {
                            UseHeaderRow = true
                        }
                    });
                    cbosheet.Items.Clear();
                    foreach (DataTable dt in result.Tables)
                        cbosheet.Items.Add(dt.TableName);
                    reader.Close();
                }
                catch 
                {
                    MessageBox.Show("error");
                }
            }
        }
    }

    private void cbosheet_SelectedIndexChanged(object sender, EventArgs e)
    {
        dataGridView1.DataSource = result.Tables[cbosheet.SelectedIndex];
    }

    private void toolStripButton5_Click(object sender, EventArgs e)
    {

    }

    private void tbRefresh_Click(object sender, EventArgs e)
    {

    }
}

}

0 个答案:

没有答案