繁体   English   中英

如何将导入的数据用作数据库?

[英]How can I use imported data as a database?

我目前有一个程序,可以将Excel数据以表格格式导入到datgrid中。

代码在这里:

 private void browse_Click(object sender, EventArgs e)
    {
        OpenFileDialog opfd = new OpenFileDialog();
        if (opfd.ShowDialog() == DialogResult.OK)
            textselect.Text = opfd.FileName;
    }

    private void showdata_Click(object sender, EventArgs e)
    {
        try {
            System.Data.OleDb.OleDbConnection MyConnection;
            System.Data.DataSet DtSet;
            System.Data.OleDb.OleDbDataAdapter MyCommand;
            MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + textselect.Text + "; Extended Properties = Excel 8.0");
            MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [" + textchoice.Text + "$]", MyConnection);
            MyCommand.TableMappings.Add("Table", "TestTable");
            DtSet = new System.Data.DataSet();
            MyCommand.Fill(DtSet);
            dataGridView.DataSource = DtSet.Tables[0];
            MyConnection.Close();

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }

浏览和显示数据是一个按钮,而文本选择和文本选择是文本框。

这样就成功创建了一个我想在图表上绘制的表格。

我当前的图表程序使用的数据库必须手动将数据插入其中,但是我想使用该程序为我导入的数据。

当前图表的代码(从简单数据库中提取):

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

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

            }

            private void btnSave_Click(object sender, EventArgs e)
            {
                try
                {
                    stocksBindingSource.EndEdit();
                    stocksTableAdapter.Update(database.Stocks);
                    Refresh();
                    MessageBox.Show("Your data has been successfully saved.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch(Exception ex)
                {
                    MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

            private void btnLoad_Click(object sender, EventArgs e)
            {
                //Clear Grid
                chart.ChartAreas["ChartArea1"].AxisX.MajorGrid.LineWidth = 0;
                chart.ChartAreas["ChartArea1"].AxisY.MajorGrid.LineWidth = 0;
                //
                chart.Series["Daily"].XValueMember = "Day";
                chart.Series["Daily"].YValueMembers = "High,Low,Open,Close";
                chart.Series["Daily"].XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Date;
                chart.Series["Daily"].CustomProperties = "PriceDownColor=Red,PriceUpColor=Green";
                //chart.Series["Daily"]["OpenCloseStyle"] = "Triangle";
                chart.Series["Daily"]["ShowOpenClose"] = "Both";
                chart.DataManipulator.IsStartFromFirst = true;
                chart.DataSource = database.Stocks;
                chart.DataBind();
            }

是否可以将导入的数据分配为数据集供我的图表使用?

我能否从发布的第一组代码中加载新数据?

理想情况下,我想利用已设置的“加载”按钮,而无视或重新利用已创建的数据库。

提前致谢!

我认为这段代码对您有用。当我选择Excel文件时,这里有浏览按钮。您将其导入到gridview中。

  private void btnBrowse_Click(object sender, EventArgs e)
      {
          string filePath = string.Empty;

           OpenFileDialog file = new OpenFileDialog();

           if (file.ShowDialog() == System.Windows.Forms.DialogResult.OK)
          {
               filePath = file.FileName; //get the path of the file  
                ReadExcel(filePath);
           }
     } 

这里我有ReadExcel方法。 方法从excel读取数据并传递到datatable中。

  DataTable table = new DataTable();

      private void ReadExcel(string filePath)
      {

                  if (!string.IsNullOrEmpty(filePath))
                  {
                          ExcelEngine excelEngine = new ExcelEngine();

                         IWorkbook workbook = excelEngine.Excel.Workbooks.Open(filePath);
                              IWorksheet worksheet = workbook.Worksheets[0];

                        table = worksheet.ExportDataTable(worksheet.UsedRange, ExcelExportDataTableOptions.ColumnNames);
                              YourDatagridviewName.DataSource = table;
                              YourDatagridviewName.Refresh();
                  }
                  else
                  {
                              MessageBox.Show("No File Selected");
                  }

      }

最后,您只需在gridview DataSource中传递数据表即可。

谢谢。!

在此处发布完整代码以进行学习

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;

namespace StockCharts
{
public partial class Form1 : Form
{
    System.Data.DataSet DtSet = new System.Data.DataSet();
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        // TODO: This line of code loads data into the 'database.Stocks' table. You can move, or remove it, as needed.
        // this.stocksTableAdapter.Fill(this.database.Stocks);
        LoadData();
    }

    private void LoadData()
{
    try {
            System.Data.OleDb.OleDbConnection MyConnection;
            // System.Data.DataSet DtSet;
            System.Data.OleDb.OleDbDataAdapter MyCommand;
            MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + textselect.Text + "; Extended Properties = Excel 8.0");
            MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [" + textchoice.Text + "$]", MyConnection);
            MyCommand.TableMappings.Add("Table", "TestTable");
            // DtSet = new System.Data.DataSet();
            MyCommand.Fill(DtSet);
            dataGridView.DataSource = DtSet.Tables[0];
            MyConnection.Close();

        }
        catch (Exception ex)
        {
         MessageBox.Show(ex.ToString());
        }
}       

    private void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            stocksBindingSource.EndEdit();
            stocksTableAdapter.Update(database.Stocks);
            Refresh();
            MessageBox.Show("Your data has been successfully saved.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    private void btnLoad_Click(object sender, EventArgs e)
    {
        //Clear Grid
        chart.ChartAreas["ChartArea1"].AxisX.MajorGrid.LineWidth = 0;
        chart.ChartAreas["ChartArea1"].AxisY.MajorGrid.LineWidth = 0;
        //
        chart.Series["Daily"].XValueMember = "Day";
        chart.Series["Daily"].YValueMembers = "High,Low,Open,Close";
        chart.Series["Daily"].XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Date;
        chart.Series["Daily"].CustomProperties = "PriceDownColor=Red,PriceUpColor=Green";
        //chart.Series["Daily"]["OpenCloseStyle"] = "Triangle";
        chart.Series["Daily"]["ShowOpenClose"] = "Both";
        chart.DataManipulator.IsStartFromFirst = true;
        //chart.DataSource = database.Stocks;
        chart.DataSource = DtSet.Tables[0];
        chart.DataBind();
    }

    private void dataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {

    }

    private void chart_Click(object sender, EventArgs e)
    {

    }
    private void browse_Click(object sender, EventArgs e)
    {
        OpenFileDialog opfd = new OpenFileDialog();
        if (opfd.ShowDialog() == DialogResult.OK)
            textselect.Text = opfd.FileName;
    }

    private void showdata_Click(object sender, EventArgs e)
    {
        try {
            System.Data.OleDb.OleDbConnection MyConnection;
           // System.Data.DataSet DtSet;
            System.Data.OleDb.OleDbDataAdapter MyCommand;
            MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + textselect.Text + "; Extended Properties = Excel 8.0");
            MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [" + textchoice.Text + "$]", MyConnection);
            MyCommand.TableMappings.Add("Table", "TestTable");
            DtSet = new System.Data.DataSet();
            MyCommand.Fill(DtSet);
            dataGridView.DataSource = DtSet.Tables[0];
            MyConnection.Close();

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    //
    }
}
}

这是Peeyush Singh https://stackoverflow.com/users/1367497/peeyush-singh带给我的最终代码!

此代码在启动时确实会产生错误,即: 这里

但是该程序非常运行,并且将excel数据输入到数据表和图表中。

再次感谢PEEYUSH SINGH https://stackoverflow.com/users/1367497/peeyush-singh

您的评论How could I link showdata function to a newly made datatable?有些困惑, How could I link showdata function to a newly made datatable?

这就是我的假设: btnLoad_Click是您现有的函数,与Form1_Load结合使用可帮助您根据插入数据库中的数据来绘制图表。 现在,这些数据来自在showdata_Click中加载的excel文件。 从excel加载数据后,我假设您将其保存在数据库中,然后在图表中进行绘制。

您要删除将数据保存到数据库中并直接将excel中加载的数据绑定到图表数据源的步骤。

您可以通过更改图表的数据源chart.DataSource = database.Stocks;来完成此chart.DataSource = database.Stocks; 如果将其绑定到自己的数据表datatable chart.DataSource = DtSet.Tables[0]; ,则代替此方法datatable chart.DataSource = DtSet.Tables[0]; ,它应该可以工作(只要您的表和stocks表的结构相同)。

发布代码后,所做的更改使数据集公开,并以表单加载而不是按钮单击事件加载数据。

public partial class Form1 : Form
        {
        System.Data.DataSet DtSet = new System.Data.DataSet();

            public Form1()
            {
                InitializeComponent();
            }

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

                // this.stocksTableAdapter.Fill(this.database.Stocks);
                   LoadData();

            }

    private void LoadData()
    {
        try {
                System.Data.OleDb.OleDbConnection MyConnection;
                // System.Data.DataSet DtSet;
                System.Data.OleDb.OleDbDataAdapter MyCommand;
                MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + textselect.Text + "; Extended Properties = Excel 8.0");
                MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [" + textchoice.Text + "$]", MyConnection);
                MyCommand.TableMappings.Add("Table", "TestTable");
                // DtSet = new System.Data.DataSet();
                MyCommand.Fill(DtSet);
                dataGridView.DataSource = DtSet.Tables[0];
                MyConnection.Close();

            }
            catch (Exception ex)
            {
             MessageBox.Show(ex.ToString());
            }
    }       

            private void btnLoad_Click(object sender, EventArgs e)
            {
                // rest of the function stays same, only change the line shown below
                // chart.DataSource = database.Stocks;
        chart.DataSource = DtSet.Tables[0];

            }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM