[英]Getting Excel sheetname and add them to comboBox
我正在嘗試向我的應用程序中添加功能,以便用戶可以從comboBox中選擇工作表。 但是我遇到了一些麻煩,我需要一些幫助! 我已經能夠讀取默認工作表名稱,因此以前能夠讀取excel文件。 但是現在我可以將工作表名稱放入我的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中看到工作Cannot find table -1
而不是內容
首先,在表單中使用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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.