winform中导入excel表格

winform中导入表格的方法有很多种,这里是用Gridview来存放从表格中导入的数据的,当然在此之前你要先从工具栏中拖一个openFileDialog进来才能用

//导入按钮点击事件

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;
}

其实导入excel和从数据库中存取数据的原理是一样的,从excel中读取数据的操作类似于从数据库中取数据的操作,其中string strSQL = “select 工号 as LICENSE_NO, 姓名 as DRIVER_NAME, 年龄as OIL_COUNT from [Sheet1$]”;中的工号姓名年龄一定要有对应的LICENSE_NO、DRIVER_NAME、OIL_COUNT 列,不然会报错

猜你喜欢

转载自blog.csdn.net/s_156/article/details/110422581