[英]Get more DataTables from an Excel file
我在Excel中遇到这种情况:
...我需要阅读此文件,但是,如何查看,有两种数据:
我有一些阅读表的困难。
这是我当前的实现:
public void Reader()
{
IExcelDataReader excel = ExcelReaderFactory.CreateOpenXmlReader(FileUpload1.PostedFile.InputStream);
// Fill datatable:
DataSet dt = excel.AsDataSet();
DataTable dataTable = dt.Tables["sheetName"];
// With the position of the cell:
string name1 = GetCellValue("C2", dataTable);
string surname1 = GetCellValue("C3", dataTable);
myLabel1 = name1 + " " + surname1;
string name2 = GetCellValue("C5", dataTable);
string surname2 = GetCellValue("C6", dataTable);
myLabel2 = name2 + " " + surname2;
string name3 = GetCellValue("F2", dataTable);
string surname3 = GetCellValue("F3", dataTable);
myLabel3 = name3 + " " + surname3;
string name4 = GetCellValue("F5", dataTable);
string surname4 = GetCellValue("F6", dataTable);
myLabel4 = name4 + " " + surname4;
// The table:
DataTable table = new DataTable();
table.Columns.Add("ColumnA");
table.Columns.Add("ColumnB");
table.Columns.Add("ColumnC");
table.Columns.Add("Total");
table.Columns.Add("Result");
DataRow newRow;
foreach (DataRow row in dataTable.AsEnumerable().Skip(9).Take(100))
{
newRow = dtSinistri.NewRow();
newRow["ColumnA"] = row[1]; // I have discover this index with the debug... :(
newRow["ColumnB"] = row[3];
newRow["ColumnC"] = row[5];
newRow["Total"] = row[7];
newRow["Result"] = row[8];
dtSinistri.Rows.Add(newRow);
}
myGridView.DataSource = table;
myGridView.DataBind();
}
/// <summary>Get the value from the cell.
/// For example: 'C5' return "Guybrush"
/// </summary>
private string GetCellValue(string codeCell, DataTable dt)
{
Regex regex = new Regex("([0-9]+)(.*)");
string HDR = "Yes";
string[] substrings = regex.Split(codeCell);
string columnLetter = substrings[0];
int columnNumber = ColumnLetterToNumber(columnLetter);
int num = (HDR == "Yes") ? 2 : 1; // if first row is an header then num=2, else num=1
int rowNumber = Int32.Parse(substrings[1]) - num;
string s = dt.Rows[rowNumber][columnNumber].ToString();
return s;
}
/// <summary>transform the letter in a column index</summary>
private static int ColumnLetterToNumber(string columnName)
{
columnName = columnName.ToUpperInvariant();
int sum = 0;
for (int i = 0; i < columnName.Length; i++)
{
sum *= 26;
char letter = columnName[i];
sum += (letter - ('A' - 1));
}
sum--;
return sum;
}
... 这有效 。 但是我想要一种自动从excel文件中获取表格的方法,例如查询或其他方法。 有什么建议吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.