Click here to Skip to main content
14,934,103 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
how to specify 6 columns and name them in datagridview so when i import an excel sheet with missing columns it adds the missing columns, keep the content empty and arrange the columns based on what i specify in datagridview note: column name does not change

for example i specify column A,B,C,D in datagridview the excel sheet it has the same column name but some of them are missing for example (A,C)

What I have tried:

this is what i did for importing excel sheet in to the application

C#
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 excelreaderdesktop
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog fil = new OpenFileDialog();
            fil.ShowDialog();
            string path = fil.FileName.ToString();
            ExcelFileReader(path);
        }

        public void ExcelFileReader(string path)
        {
            var stream = File.Open(path, FileMode.Open, FileAccess.Read);
            var reader = ExcelReaderFactory.CreateReader(stream);
            var result = reader.AsDataSet();
            var tables = result.Tables.Cast<DataTable>();
            foreach(DataTable table in tables)
            {
                dataGridView1.DataSource = table;
            }
        }
    }
}
Posted
Updated 9-May-21 11:11am
v3
Comments
Gerry Schmitz 4-Apr-21 12:41pm
   
You create a multi-table dataset; then assign each table to the same DataSource. Go back to the drawing board.

1 solution

So assuming your columns list is static (which you imply), you can read the dataTable columns list after reading in the excel sheet, as you have done, and the missing ones can be added to the data table definition. DataTable.Columns.Add (DataColumn).
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900