winforms 导入编号后DataGridView为空

b5lpy0ml  于 2023-02-05  发布在  其他
关注(0)|答案(1)|浏览(116)
namespace WinFormsApp4
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Load_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog ofd = new OpenFileDialog())
            {
                ofd.Filter = "Excel Files only | *.xlsx; *.xls; *.csv;" ;
                ofd.Title = "Choose the file";
                if (ofd.ShowDialog() == DialogResult.OK)
                    label1.Text = ofd.FileName;
            }
        }

        private void Import_Click_1(object sender, EventArgs e)
        {
            Microsoft.Office.Interop.Excel.Application xlapp;
            Microsoft.Office.Interop.Excel.Workbook xlworkbook;
            Microsoft.Office.Interop.Excel.Worksheet xlworksheet;
            Microsoft.Office.Interop.Excel.Range xlrange;
            try
            {
                xlapp = new Microsoft.Office.Interop.Excel.Application();
                xlworkbook = xlapp.Workbooks.Open(label1.Text);
                xlworksheet = xlworkbook.Worksheets["List1"];
                xlrange = xlworksheet.UsedRange;

                DataMore.ColumnCount = xlrange.Columns.Count;
    
                DataMore.ColumnCount = 6;
                DataMore.Columns[0].HeaderText = "Datum";
                DataMore.Columns[1].HeaderText = "Energia";
                DataMore.Columns[2].HeaderText = "AC výkon";
                DataMore.Columns[3].HeaderText = "napetie siete";
                DataMore.Columns[4].HeaderText = "AC prud";
                DataMore.Columns[5].HeaderText = "DC napetie";

                foreach (DataGridViewRow row in DataMore.Rows)
                {
             
                }
                // for (int xlrow = 1; xlrow <= xlrange.Rows.Count; xlrow++)
                // {
                //   DataMore.Rows.Add(xlrange.Cells[xlrow, 1].Text, xlrange.Cells[xlrow, 2].Text, xlrange.Cells[xlrow, 3].Text,
                //     xlrange.Cells[xlrow, 4].Text);
                // }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}

嗨,首先我完全初学C#编程。我尝试从Excel导入数字到datagridview。所有的数字都在1列,看起来像这样:
一、二、三、四、五、六、七、八、九、十
所有的数字都不是真实的因为原来的excel有数字,他收集24/7过去5年和它的吨的数字,所以我创建自己的小excel...
我只是想创建程序,我从Excel导入数字,然后我删除数字“0”,然后试图创建图表...但我在开始卡住了,你能帮我吗?

nr7wwzry

nr7wwzry1#

您的问题是关于使用Microsoft.Office.Interop.Excel将Excel数据导入到DataGridView控件,并指出视图为空的问题。查看您的代码时,我还注意到一些Excel对象未被正确处理,这可能导致Excel的多个示例运行(请查看任务管理器)。
因此,我想从头开始,分四个步骤看看如何妥善地进行这项工作。

记录类

创建一个名为Record的类来表示一行数据。

class Record
{
    [DisplayName("Datum")]
    public DateTime Datum { get; set; }

    [DisplayName("Energia")]
    public double Energia { get; set; }

    [DisplayName("AC výkon")]
    public double ACvýkon { get; set; }

    [DisplayName("napetie siete")]
    public double napetiesiete { get; set; }

    [DisplayName("AC prud")]
    public double ACprud { get; set; }

    [DisplayName("DC napetie")]
    public double DCnapetie { get; set; }
}

自动配置数据网格视图

创建一个BindingList<Record>并将其附加到数据网格视图的DataSource属性。

public partial class MainForm : Form
{
    BindingList<Record> Records { get; } = new BindingList<Record>();

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        dataGridView.DataSource = Records;

        #region F O R M A T    C O L U M N S
        Records.Add(new Record()); // <- Auto-generate columns
        foreach (DataGridViewColumn column in dataGridView.Columns)
        {
            column.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            if (column.Index > 1) column.DefaultCellStyle.Format = "F2";
        }
        Records.Clear();
        #endregion F O R M A T    C O L U M N S          
    }
    .
    .
    .
}

配置Excel互操作创建和释放

public MainForm()
{
    InitializeComponent();
    // Create
    _xlApp = new Microsoft.Office.Interop.Excel.Application();
    // When in the future the main form closes, dispose the Excel interop.
    Disposed += (sender, e) =>
    {
        _xlBook?.Close();
        _xlApp.Quit();
    }; 
    buttonImport.Click += Import_Click_1;
}
private readonly Microsoft.Office.Interop.Excel.Application _xlApp;
private Workbook _xlBook = null;

导入数据(在本例中是从预定的文件位置导入)

由于Records的数据源绑定,当您添加到该集合时,它将显示在数据网格视图中,而不必处理控件本身。
因此,在Excel中打开工作簿和工作表后,捕获所有使用过的单元格的范围并解析该信息以创建Record示例,然后将它们添加到Records集合中。

private void Import_Click_1(object sender, EventArgs e)
{
    Records.Clear();
    string filePath = Path.Combine(
        AppDomain.CurrentDomain.BaseDirectory,
        "Excel",
        "testdata.xlsx");

    _xlBook = _xlApp.Workbooks.Open(filePath);
    Worksheet 
        xlSheet = _xlBook.Sheets[1];
    Range 
        xlRange = xlSheet.UsedRange,
        range;
    List<string> 
        headers = new List<string>(),
        line = new List<string>();

    for (int i = 1; i <= xlRange.Rows.Count; i++)
    {
        if (i.Equals(1))
        {
            for (int j = 1; j <= xlRange.Columns.Count; j++)
            {
                range = xlRange.Cells[i, j];
                headers.Add(range.Value2);
            }
        }
        else
        {
            var record = new Record();
            for (int j = 1; j <= xlRange.Columns.Count; j++)
            {
                range = xlRange.Cells[i, j];
                var name = headers[j - 1];
                switch(name)
                {
                    case "Datum": record.Datum = DateTime.FromOADate(range.Value2); break;
                    case "Energia": record.Energia = range.Value2; break;
                    case "AC výkon": record.ACvýkon = range.Value2; break;
                    case "napetie siete": record.napetiesiete = range.Value2; break;
                    case "AC prud": record.ACprud = range.Value2; break;
                    case "DC napetie": record.DCnapetie = range.Value2; break;
                    default:
                        Debug.Assert(false, $"Not recognized: '{name}'");
                        break;
                }
            }
            Records.Add(record);
        }
    }
}

相关问题