Я использую Excel 2016, сообщество Visual Studio 2019 и хочу экспортировать лист Excel в представление таблицы данных. Кроме того, я хотел бы выбрать определенные столбцы, которые затем будут приняты. Программа работает с функцией заполнения набора данных, а затем программа работает с перехватом без отображения сообщения об ошибке
private void Cmd_Fbd_Data_List_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog openFileDialog1 = new OpenFileDialog(); //create openfileDialog Object
openFileDialog1.Filter = "XML Files (*.xml; *.xls; *.xlsx; *.xlsm; *.xlsb) |*.xml; *.xls; *.xlsx; *.xlsm; *.xlsb";//open file format define Excel Files(.xls)|*.xls| Excel Files(.xlsx)|*.xlsx|
openFileDialog1.FilterIndex = 3;
openFileDialog1.Multiselect = false; //not allow multiline selection at the file selection level
openFileDialog1.Title = "Open Text File-R13"; //define the name of openfileDialog
openFileDialog1.InitialDirectory = @"Desktop"; //define the initial directory
if (openFileDialog1.ShowDialog() == DialogResult.OK) //executing when file open
{
string pathName = openFileDialog1.FileName;
string fileName = System.IO.Path.GetFileNameWithoutExtension(openFileDialog1.FileName);
DataTable tbContainer = new DataTable();
string strConn = string.Empty;
FileInfo file = new FileInfo(pathName);
if (!file.Exists) { throw new Exception("Error, file doesn't exists!"); }
string extension = file.Extension;
switch (extension)
{
case ".xls":
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
break;
case ".xlsx":
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pathName + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'";
break;
default:
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
break;
}
String name = "DPL";// is the Name of the first Sheet
OleDbConnection con = new OleDbConnection(strConn);
OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]", con);
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
DataTable data = new DataTable();
// up to this line the programm works after that the Exception shows up
sda.Fill(data);
Dgv_Data_List.DataSource = data;
}
}
catch (Exception)
{
MessageBox.Show("Error!");
}
}