我正在查看一些提供给我的代码,以尝试了解如何将 excel 电子表格加载到DataTable
. 我已经让那部分工作了,或者至少我认为它有效,因为它没有异常。我现在想做的是检查是否填充了 DataTable。我遇到的问题是Form
从类中识别列表。
这是我的课程的代码:
namespace WindowsFormsApplication12
{
class Class1
{
public List<DataTable> ImportExcel(string FileName)
{
List<DataTable> _dataTables = new List<DataTable>();
string _ConnectionString = string.Empty;
string _Extension = Path.GetExtension(FileName);
if (_Extension.Equals(".xls", StringComparison.CurrentCultureIgnoreCase))
{
_ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + FileName + ";Extended Properties=Excel 12.0;";
}
else if (_Extension.Equals(".xlsx", StringComparison.CurrentCultureIgnoreCase))
{
_ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FileName + ";Extended Properties=Excel 12.0 Xml;";
}
DataTable dataTable = null;
var count = 0;
using (OleDbConnection oleDbConnection = new OleDbConnection(string.Format(_ConnectionString, FileName)))
{
oleDbConnection.Open();
DataTable dbSchema = oleDbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables_Info, null);
foreach (DataRow item in dbSchema.Rows)
{
using (OleDbCommand oleDbCommand = new OleDbCommand())
{
oleDbCommand.Connection = oleDbConnection;
oleDbCommand.CommandText = string.Format("SELECT * FROM [Sheet1$]", item["TABLE_NAME"].ToString());
using (OleDbDataAdapter oleDbDataAdapter = new OleDbDataAdapter())
{
if (count < 3)
{
oleDbDataAdapter.SelectCommand = oleDbCommand;
dataTable = new DataTable(item["TABLE_NAME"].ToString());
oleDbDataAdapter.Fill(dataTable);
_dataTables.Add(dataTable);
count++;
}
}
}
}
}
return _dataTables;
}
}
}
这是我的表单的代码:
namespace WindowsFormsApplication12
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string fileName = textBox1.Text;
Class1 ext = new Class1();
if (string.IsNullOrEmpty(fileName))
MessageBox.Show("Please enter a file extension");
else
ext.ImportExcel(fileName);
}
}
}
我尝试了一些事情,例如:
List<DataTable> ldt = new Class1.ImportExcel
ListBox.Items.Add(ext.ImportExcel._dataTables)
连同其他一些东西,但似乎没有任何效果。我已经用谷歌搜索了如何调用 aList
并且没有任何工作。我在DataTable
之前的练习中调用了 a ,但我无法根据这段代码定制它。如果有一些文件可以帮助我,或者如果我很接近,请把我推向正确的方向。先感谢您。