C#读取Excel文件显示到Datagird控件中 ,读取Execl过程有问题,请教
问题是:
在导入的过程中有几个字段提示:无法将类型为“System.DBNull”的对象强制转换为类型“System.String”,只有第一个字段,被遍历出来其他字段一遍历就提示上述问题?请教了?
源码:
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.OleDb;
using System.Data;
using Microsoft.Win32;
using System.Data.SqlClient;
namespace 读取Execl数据
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
/// <summary>
/// 读取Execl文件返回DataSet方法
/// </summary>
/// <returns>返回结果集</returns>
public DataSet ReaderExecl(string sql)
{
string conn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + txtfiles.Text +";Extended Properties=Excel 8.0;";
using (OleDbConnection OleCon = new OleDbConnection(conn))
{
OleCon.Open();
using (OleDbCommand OleCmd = new OleDbCommand())
{
DataSet Myds = new DataSet();
OleCmd.CommandText =sql; //"select * from [sheet1$]";
OleDbDataAdapter adapter = new OleDbDataAdapter();
OleCmd.Connection = OleCon;
adapter.SelectCommand=OleCmd;