【问题标题】:Accessing a table in an excel spreadsheet using C#使用 C# 访问 Excel 电子表格中的表
【发布时间】:2014-07-14 16:58:32
【问题描述】:
我正在编写一个程序(在 C# 中,使用 Microsoft.Office.Interop.Excel)读取 Excel 电子表格并将过滤器等应用于其中的数据。但是,我正在努力解决一些问题,即如何“获取”代表我正在使用的数据表的表对象。我也希望能够通过标题访问列,所以我假设我需要 DataTable 命名空间。但是,我似乎不知道该怎么做。
这是我的代码的粗略框架:
private void Process(Workbook workBook)
{
try
{
Worksheet sheet = workBook.Sheets["x"];
Range range = sheet.UsedRange;
// what goes here in order to access columns by name?
}
catch (Exception ex)
{
}
}
我真的不知道该怎么做,所以非常欢迎任何帮助,以及有关如何使用 Microsoft.Office.Excel.Interop 的有用文章的任何建议。我真的找不到很多适合我需要的资源。非常感谢!
【问题讨论】:
-
-
-
好的。请记住,如果您想将其移动到 ASP.NET 中,请使用 Interop 库 don't work。您需要使用替代库,例如 EPPlus。这些库中的大多数都具有更易于使用的优点,并且它们避免了运行“隐藏”Office 窗口(并且不需要安装 Office)带来的一些问题。
-
标签:
c#
excel
ms-office
office-interop
excel-interop
【解决方案1】:
我一直在使用 EPPLUS,你可以通过 NuGet 获得它。使用EPPLUS 而不是 Microsoft.Office.Excel.Interop
自切片面包以来最好的东西。
这是一个stackoverflow 链接,显示如何导出到 Excel
这里是如何将excel导入数据表
var pck = new OfficeOpenXml.ExcelPackage();
pck.Load(new System.IO.FileInfo(path).OpenRead());
var ws = pck.Workbook.Worksheets["Worksheet1"];
DataTable tbl = new DataTable();
var hasHeader = true;
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);
}
【解决方案2】:
以下代码 sn-p 演示了使用 C# 和 Microsoft.Office.Interop.Excel 将数据从 .NET DataTable 导出到 Excel 工作簿的技术:
internal static bool Export2Excel(DataTable dataTable, bool Interactive)
{
object misValue = System.Reflection.Missing.Value;
// Note: don't put Microsoft.Office.Interop.Excel in 'using' section:
// it may cause ambiguity w/System.Data because both have DataTable obj
// use in-place reference as shown below
Microsoft.Office.Interop.Excel.Application _appExcel = null;
Microsoft.Office.Interop.Excel.Workbook _excelWorkbook = null;
Microsoft.Office.Interop.Excel.Worksheet _excelWorksheet = null;
try
{
// excel app object
_appExcel = new Microsoft.Office.Interop.Excel.Application();
// excel workbook object added to app
_excelWorkbook = _appExcel.Workbooks.Add(misValue);
_excelWorksheet = _appExcel.ActiveWorkbook.ActiveSheet as Microsoft.Office.Interop.Excel.Worksheet;
// column names row (range obj)
Microsoft.Office.Interop.Excel.Range _columnsNameRange;
_columnsNameRange = _excelWorksheet.get_Range("A1", misValue).get_Resize(1, dataTable.Columns.Count);
// column names array to be assigned to _columnNameRange
string[] _arrColumnNames = new string[dataTable.Columns.Count];
// assign array to column headers range, make 'em bold
_columnsNameRange.set_Value(misValue, _arrColumnNames);
_columnsNameRange.Font.Bold = true;
// populate data content row by row
for (int Idx = 0; Idx < dataTable.Rows.Count; Idx++)
{
_excelWorksheet.Range["A2"].Offset[Idx].Resize[1, dataTable.Columns.Count].Value =
dataTable.Rows[Idx].ItemArray;
}
// Autofit all Columns in the range
_columnsNameRange.Columns.EntireColumn.AutoFit();
// make visible and bring to the front (note: warning due to .Activate() ambiguity)
if (Interactive) { _appExcel.Visible = Interactive; _excelWorkbook.Activate(); }
// // save and close if Interactive flag not set
else
{
// Excel 2010 - "14.0"
// Excel 2007 - "12.0"
string _ver = _appExcel.Version;
double _dblVer = double.Parse(_ver);
string _fileName ="TableExported_" +
DateTime.Today.ToString("yyyy_MM_dd") + "-" +
DateTime.Now.ToString("hh_mm_ss");
// check version and select file extension
if (_dblVer >= 12) { _fileName += ".xlsx"; }
else { _fileName += ".xls"; }
// save and close Excel workbook in Document Dir
string _subDir = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), _expDir);
// create if target directory doesn't exists
if (!System.IO.Directory.Exists(_subDir)) { System.IO.Directory.CreateDirectory(_subDir); }
// format the full File path
string _pathFile = System.IO.Path.Combine(_subDir, _fileName);
// save file and close Excel workbook
_excelWorkbook.Close(true, _pathFile, misValue);
}
// quit excel app process
if (_appExcel != null)
{
_appExcel.UserControl = false;
_appExcel.Quit();
}
return true;
}
catch (Exception ex)
{
// alternatively you can show Error message
throw;
}
finally
{
// release ref vars
if (_appExcel != null)
{
_excelWorksheet = null;
_excelWorkbook = null;
_appExcel = null;
misValue = null;
}
}
}
希望这会有所帮助。问候,