我创建了一个从Excel文件中读取的控制台应用程序。我想获取所有文档编号并将其放在一个数组中以便进行搜索。 我能够找到包含数据“DocumentNumber”的单元格,例如$ F $ 5。如何遍历F列中的行? 我有以下代码:
public static void Main(string[] args)
{
string address;
string next;
try
{
Excel.ApplicationClass excel = new Excel.ApplicationClass();
Excel.Workbook workbook = excel.Workbooks.Open(@"D:\sample.xls", 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);
Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Sheets["Sheet1"];
Excel.Range docNumber = worksheet.Cells.Find("DocumentNumber", worksheet.Cells[1, 1], Excel.XlFindLookIn.xlValues,
Excel.XlLookAt.xlPart, Missing.Value, Excel.XlSearchDirection.xlNext,
false, Missing.Value, Missing.Value);
if(docNumber != null){
address = docNumber.get_Address(true, true, Excel.XlReferenceStyle.xlA1, Missing.Value, Missing.Value);
Console.WriteLine(address);
}
}
catch (Exception err)
{
Console.WriteLine(err.Message);
}
}
提前致谢。
答案 0 :(得分:1)
请仔细研究。它遍历每一行和每一行。
string address;
string next;
try {
Excel.ApplicationClass excel = new Excel.ApplicationClass();
object Missing = Type.Missing;
FileInfo fInfo = new FileInfo(@"D:\sample.xls");
if(fInfo.Exists) {
Excel.Workbook workbook = excel.Workbooks.Open(@"D:\sample.xls", Missing, Missing,
Missing, Missing, Missing, Missing, Missing,
Missing, Missing, Missing, Missing, Missing,
Missing, Missing);
Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Sheets["Sheet1"];
Excel.Range docNumber = worksheet.Cells.Find("DDEC", worksheet.Cells[1, 1],
Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlPart, Missing, Excel.XlSearchDirection.xlNext, false, Missing, Missing);
if(docNumber != null) {
address = docNumber.get_Address(true, true, Excel.XlReferenceStyle.xlA1, Missing, Missing);
docNumber = worksheet.UsedRange;
for (int rCnt = 1; rCnt <= docNumber.Rows.Count; rCnt++) {
for (int cCnt = 1; cCnt <= docNumber.Columns.Count; cCnt++) {
string str = (string)(docNumber.Cells[rCnt, cCnt] as Excel.Range).Value2;
MessageBox.Show(str);
}
}
Console.WriteLine(address);
}
}
}
答案 1 :(得分:1)
使用OLEDB读取数据会不会更容易?更清晰的语法,然后您可以预先返回返回的DataTable。
答案 2 :(得分:0)