[英]Adding MS Excel library to VS 2015 Express
I have VS Express 2015 installed and MS office 2007 on my pc. 我的电脑上安装了VS Express 2015和MS Office 2007。 I need to read some values from an excel sheet.
我需要从Excel工作表中读取一些值。 I added Microsoft Office 12.0 Object Library but I can't use this
我添加了Microsoft Office 12.0对象库,但是我不能使用它
using Microsoft.Office.Interop.Excel;
I get the following error : The type or namespace name 'Interop' does not exist in the namespace 'Microsoft.Office' (are you missing an assembly reference?) 我收到以下错误:类型或名称空间名称“ Interop”在名称空间“ Microsoft.Office”中不存在(您是否缺少程序集引用?)
As you are looking to read some values from an excel sheet EPPlus is grate and easy way to work with Excel file. 当您希望从Excel工作表中读取一些值时, EPPlus是使用Excel文件的一种简单而便捷的方法。 This is a wrapper for Open office XML.
这是Open Office XML的包装。
public static DataTable getDataTableFromExcel(string path)
{
using (var pck = new OfficeOpenXml.ExcelPackage())
{
using (var stream = File.OpenRead(path))
{
pck.Load(stream);
}
var ws = pck.Workbook.Worksheets.First();
DataTable tbl = new DataTable();
bool hasHeader = true; // adjust it accordingly( i've mentioned that this is a simple approach)
foreach (var firstRowCell in ws.Cells[1, 1, 1, ws.Dimension.End.Column])
{
tbl.Columns.Add(hasHeader ? firstRowCell.Text : string.Format("Column {0}", firstRowCell.Start.Column));
}
var startRow = hasHeader ? 2 : 1;
for (var rowNum = startRow; rowNum <= ws.Dimension.End.Row; rowNum++)
{
var wsRow = ws.Cells[rowNum, 1, rowNum, ws.Dimension.End.Column];
var row = tbl.NewRow();
foreach (var cell in wsRow)
{
row[cell.Start.Column - 1] = cell.Text;
}
tbl.Rows.Add(row);
}
return tbl;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.