我正在尝试在我的应用程序中添加一项功能,用户可以从comboBox中选择工作表。但是我遇到了一些障碍,我需要一些帮助!之前我已经能够读取excel文件,因为我已经打印了默认的工作表名称。但是现在我能够将sheetname放到我的comboBox中,但我现在似乎无法阅读excel文件了?请帮帮我
public static DataTable ExcelToDataTable (string fileName)
{
using (var stream = File.Open(fileName, FileMode.Open, FileAccess.Read))
{
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
var result = reader.AsDataSet(new ExcelDataSetConfiguration()
{
UseColumnDataType = true,
ConfigureDataTable = (data) => new ExcelDataTableConfiguration()
{
UseHeaderRow = true
}
});
DataTableCollection table = result.Tables;
DataTable resultTable = table["Sheet1"];
return resultTable;
}
}
}
private void btnOpen_Click(object sender, EventArgs e)
{
try
{
using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "Excel 2003 Worksheet|*.xls|Excel 2007 Worksheet|*.xlsx", ValidateNames = true, Multiselect = false })
{
if (ofd.ShowDialog() == DialogResult.OK)
{
dataGridView1.DataSource = ExcelToDataTable(ofd.FileName);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
现在
public static DataSet ExcelToDataTable (string fileName)
{
using (var stream = File.Open(fileName, FileMode.Open, FileAccess.Read))
{
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
var result = reader.AsDataSet(new ExcelDataSetConfiguration()
{
UseColumnDataType = true,
ConfigureDataTable = (data) => new ExcelDataTableConfiguration()
{
UseHeaderRow = true
}
});
return result;
}
}
}
private void btnOpen_Click(object sender, EventArgs e)
{
try
{
using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "Excel 2003 Worksheet|*.xls|Excel 2007 Worksheet|*.xlsx", ValidateNames = true, Multiselect = false })
{
if (ofd.ShowDialog() == DialogResult.OK)
{
comboBox1.Items.Clear();
foreach (DataTable dt in ExcelToDataTable(ofd.FileName).Tables)
{
comboBox1.Items.Add(dt.TableName);
}
DataTableCollection table = ExcelToDataTable(ofd.FileName).Tables;
DataTable resultTable = ExcelToDataTable(ofd.FileName).Tables[comboBox1.SelectedIndex];
dataGridView1.DataSource = resultTable
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
我可以知道出了什么问题吗?我收到Cannot find table -1
的错误,但我可以看到excel中的工作表名称不是内容
答案 0 :(得分:0)
首先在表单中使用DataSet
属性:
private DataSet ExcelDateSet { get; set; }
并添加一个方法来读取它的表格,如下所示:
private DataTable GetExcelDataTable(string sheetName)
{
if (string.IsNullOrEmpty(sheetName) || !ExcelDateSet.Tables.Contains(sheetName))
{
// Notify user to select a sheet-name from your ComboBox!
// or you can return first-sheet info as default like this:
// return ExcelDateSet.Tables[0];
}
return ExcelDateSet.Tables[sheetName];
}
然后在btnOpen_Click
中设置其值,如下所示:
ExcelDataSet = ExcelToDataTable(ofd.FileName);
dataGridView1.DataSource = GetExcelDataTable(comboBox1.SelectedText);
dataGridView1.DataBind();