Import excel form in winform

There are many ways to import tables in winform. Here, Gridview is used to store the data imported from the table. Of course, you have to drag an openFileDialog from the toolbar before you can use it.

//导入按钮点击事件

private void btnImport_Click(object sender, System.EventArgs e)
{
    
    
//选择文件
this.openFileDialog1.Filter = "导入文件 (*.xls)|*.xls|所有文件 (*.*)|*.*";
                        this.openFileDialog1.Title = "选择文件";
this.openFileDialog1.RestoreDirectory = true;
                        string strFname = "";
if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
{
    
    
strFname = this.openFileDialog1.FileName; 
}
else
return;

DataSet dsBill;
try
{
    
    
dsBill = ExcelToDataSet(strFname);
}
catch(Exception err)
{
    
    
MessageBox.Show("取EXCEL数据时发生错误!\n" + err.ToString(), "提示");
return;
}

if (dsBill == null) return;
gridControl1.DataSource = dsBill;                                                 //绑定数据集 --------- 这个不会的话去看看数据集的操作吧
gridControl1.DataMember = "TableExcel";
}

                //Excel作为数据导入
private DataSet ExcelToDataSet(string xlsFilePath)
{
    
    
string strConn = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + xlsFilePath + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1';";
OleDbConnection connExcel = new OleDbConnection(strConn);

//打开文件
try
{
    
    
connExcel.Open();  
}
catch(Exception err)
{
    
    
MessageBox.Show("打开文件时发生错误!\n" + err.ToString(), "错误");
return null;
}

string strSQL = "select 工号 as LICENSE_NO, 姓名 as DRIVER_NAME, 年龄as OIL_COUNT from [Sheet1$]";

OleDbDataAdapter daXlsFile = new OleDbDataAdapter(strSQL,connExcel);

DataSet dsExcel = new DataSet();
//填充数据
try
{
    
    
daXlsFile.Fill(dsExcel,"TableExcel");
}
catch(Exception err)
{
    
    
MessageBox.Show("填充数据时发生错误!\n" + err.ToString(), "错误");
string a = err.ToString();
return null;
}

connExcel.Dispose();
return dsExcel;
}

In fact, the principle of importing excel and accessing data from the database is the same. The operation of reading data from excel is similar to the operation of fetching data from the database, where string strSQL = "select job number as LICENSE_NO, name as DRIVER_NAME, age as OIL_COUNT from [Sheet1$]”; The name and age of the job number must have the corresponding LICENSE_NO, DRIVER_NAME, OIL_COUNT columns, otherwise an error will be reported

Guess you like

Origin blog.csdn.net/s_156/article/details/110422581