首先,我很抱歉我之前曾问过这个问题,但由于在一天中的安静时间发帖,我从未得到答案。
我正在尝试将 xlsx 文档列中的数据读取到基于表单的程序上的数组列表中,这样我就可以调用各种数据位来操作或简单地显示 onscren,但无法让某些代码工作。我搜索了论坛,发现根据海报的作品,但我遇到了问题。我真的被困在这件事上,因为我从来不需要编写任何涉及 excel 的代码。
它抛出的错误是当前上下文中不存在“服务器、缺失和会话”字样。我知道 session 不是 winforms 应用程序的一部分,但不知道该怎么做。
using Microsoft.Office.Interop.Excel;
这是主要代码
string filePath = "SampleData.xlsx";
try
{
Excel.Application appExl;
Excel.Workbook workbook;
Excel.Worksheet NwSheet;
Excel.Range ShtRange;
appExl = new Excel.Application();
workbook = appExl.Workbooks.Open(filePath);
workbook = appExl.Workbooks.Open(Server.MapPath(filePath), Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
NwSheet = (Excel.Worksheet)workbook.Sheets.get_Item(1);
int Cnum = 0;
int Rnum = 0;
ShtRange = NwSheet.UsedRange;
DataTable dt = new DataTable();
for (int row = 1; row <= ShtRange.Rows.Count; row++)
{
string str = Convert.ToString((ShtRange.Cells[row, 1] as Excel.Range).Value2);
dt.Columns.Add(str);
}
workbook.Close(true);
appExl.Quit();
Session["data"] = dt;
return true;
}
catch (Exception ex)
{
return false;
}
这是更好地代表它应该是什么样的吗?
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
string FilePath = "SampleData.xlsx";
Excel.Application appExl;
Excel.Workbook workbook;
Excel.Worksheet NwSheet;
Excel.Range ShtRange;
appExl = new Excel.Application();
workbook = appExl.Workbooks.Open(FilePath);
NwSheet = (Excel.Worksheet)workbook.Sheets.get_Item(1);
int Cnum = 0;
int Rnum = 0;
ShtRange = NwSheet.UsedRange;
DataTable dt = new DataTable();
for (int row = 1; row <= ShtRange.Rows.Count; row++)
{
string str = Convert.ToString((ShtRange.Cells[row, 1] as Excel.Range).Value2);
dt.Columns.Add(str);
}
workbook.Close(true);
appExl.Quit();