我不确定这是否可以在 ASP.NET 中工作,但它可以在 WPF 中工作,所以也许你可以从中获得一些东西?
无论如何,在全球范围内:
Microsoft.Office.Interop.Excel.Application xls;
然后选择并阅读电子表格:
private void readSheet()
{
// Initialise and open file picker
OpenFileDialog openfile = new OpenFileDialog();
openfile.DefaultExt = ".xlsx";
openfile.Filter = "Office Files | *xls;.xlsx";
var browsefile = openfile.ShowDialog();
if (browsefile == true)
{
string path = openfile.FileName;
xls = new Microsoft.Office.Interop.Excel.Application();
// Dynamic File Using Uploader... Note the readOnly flag is true
Workbook excelBook = xls.Workbooks.Open(path, 0, true, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
Worksheet excelSheet = (Worksheet)excelBook.Worksheets.get_Item(1); ;
Range excelRange = excelSheet.UsedRange;
// Make default cell contents
string strCellData = String.Empty;
double douCellData;
// Initialise row and column
int rowCnt, colCnt = 0;
// Initialise DataTable
System.Data.DataTable dt = new System.Data.DataTable();
// Loop through first row of columns to make header
for (colCnt = 1; colCnt <= excelRange.Columns.Count; colCnt++)
{
string strColumn = "";
strColumn = Convert.ToString((excelRange.Cells[1, colCnt] as Range).Value2);
var Column = dt.Columns.Add();
Column.DataType = Type.GetType("System.String");
// Check & rename for duplicate entries
if (dt.Columns.Contains(strColumn))
Column.ColumnName = (strColumn + ", " + colCnt);
else
Column.ColumnName = strColumn;
}
dt.AcceptChanges();
// Fill in the rest of the cells
for (rowCnt = 2; rowCnt <= excelRange.Rows.Count; rowCnt++)
{
string strData = "";
for (colCnt = 1; colCnt <= excelRange.Columns.Count; colCnt++)
{
try
{
strCellData = Convert.ToString((excelRange.Cells[rowCnt, colCnt] as Range).Value2);
strData += strCellData + "|";
}
catch (Exception ex)
{
douCellData = (excelRange.Cells[rowCnt, colCnt] as Range).Value2;
strData += douCellData.ToString() + "|";
Console.Write(ex.ToString());
}
}
strData = strData.Remove(strData.Length - 1, 1);
dt.Rows.Add(strData.Split('|'));
}
dtGrid.ItemsSource = dt.DefaultView;
try
{
excelBook.Close(true, null, null);
}
catch (System.Runtime.InteropServices.COMException comEX)
{
Console.Write("COM Exception: " + comEX.ToString());
}
xls.Quit();
}
}