在不使用OLEDB提供程序的情况下在Excel工作表上发出select语句

时间:2017-10-18 15:32:00

标签: c# sql excel

如何在不使用任何oledb提供程序的情况下在Excel工作表上使用select语句?这是我到目前为止使用using Excel = Microsoft.Office.Interop.Excel;得到的。使用嵌套的for循环遍历每个单元格感觉不对...

// Create excel application object by calling constructor 
Excel.Application xlApp = new Excel.Application();

// Open excel file using excel object 
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"D:\Temp\file.xls");

// Open first sheet within excel document (index start at 1, not 0) 
Excel._Worksheet xlWorksheet = (Excel.Worksheet)xlWorkbook.Sheets["SheetName"];

// Get used sheet bounderies 
Excel.Range xlRange = xlWorksheet.UsedRange;

// Get row count 
int rowCount = xlRange.Rows.Count;

// Get column count 
int colCount = xlRange.Columns.Count;

//iterate over the rows and columns and print to the console as it appears in the file
for (int i = 1; i <= rowCount; i++)
{
    for (int j = 1; j <= colCount; j++)
    {
        //new line
        if (j == 1)
            Console.Write("\r\n");

        //write the value to the console if cell value ends on 'd'
        if (xlRange.Cells[i, j] != null && xlRange.Cells[i, j].Value2 != null && (xlRange.Cells[i, j].Value2.ToString()).EndsWith("d"))
            Console.Write(xlRange.Cells[i, j].Value2.ToString() + "\t");
    }
}

1 个答案:

答案 0 :(得分:0)

虽然您可以使用范围的items界面覆盖所有单元格,但是您为每行输出并有条件地跨列输出,for是正确的方法。

但是,你可以稍微收紧一下代码:

var rowCount = xlRange.Rows.Count;
var colCount = xlRange.Columns.Count;

for (int row = 1; row <= rowCount; ++row) {
    Console.WriteLine();
    for (int col = 1; col <= colCount; ++col) {
        //write the value to the console if cell value ends on 'd'
        if (xlRange.Cells[row, col]?.Value2?.ToString().EndsWith("d") ?? false)
            Console.Write(xlRange.Cells[row, col].Value2.ToString() + "\t");
    }
}