我有一个excel文档,其中包含几个表(选择数据并选择格式作为表并为其命名)。
我正在尝试打开工作簿并获取文档中的所有表。
以下代码返回工作簿中的一些部分,但不返回特定的表。
这可能吗?
public partial class Form1 : Form
{
private DataSet _excelDataSet;
public Form1()
{
InitializeComponent();
var filePath = "c:\\temp\\orderforms\\SampleOrder.xlsx";
var tmpName = Path.GetTempFileName() + Path.GetExtension(filePath);
File.Copy(filePath, tmpName);
filePath = tmpName;
var excelReader = GetExcelDataReader(filePath, true);
excelReader.IsFirstRowAsColumnNames = true;
_excelDataSet = excelReader.AsDataSet();
}
private static IExcelDataReader GetExcelDataReader(string path, bool isFirstRowAsColumnNames)
{
using (var fileStream = File.Open(path, FileMode.Open, FileAccess.Read))
{
IExcelDataReader dataReader;
if (path.EndsWith(".xls"))
dataReader = ExcelReaderFactory.CreateBinaryReader(fileStream);
else if (path.EndsWith(".xlsx"))
dataReader = ExcelReaderFactory.CreateOpenXmlReader(fileStream);
else
throw new FileToBeProcessedIsNotInTheCorrectFormatException("The file to be processed is not an Excel file");
dataReader.IsFirstRowAsColumnNames = isFirstRowAsColumnNames;
return dataReader;
}
}
private void btnLoadOrder_Click(object sender, EventArgs e)
{
DataTable dt1 = _excelDataSet.Tables[Convert.ToInt32(textBox1.Text)];
dataGridView2.DataSource = dt1;
MessageBox.Show(dt1.TableName);
}
}
答案 0 :(得分:0)
使用linqtoexcel库。可以很容易地找到有关如何使用此库的示例。
答案 1 :(得分:0)
var excel = new ExcelQueryFactory();
excel.FileName = "c:\\temp\\orderforms\\orderform.xlsx";
var order = from x in excel.NamedRange<SunglassesOrder>("Order")
where x.Qty!=""
select x;
dataGridView1.DataSource = order.ToList();