获取特定行集的最大列数

时间:2015-11-24 15:51:15

标签: c# .net excel visual-studio

如果我想在Excel中使用Visual Studio获取一组行的最大列数,该怎么做?

这是我当前的尝试,它产生整个工作表而不是指定行的最大列数。这是我对此的尝试。所有必要的东西,如使用,初始化Excel项目等都在那里,但这里没有显示。

class Sheets
{
    public Excel.Application app;  //= new Excel.Application();
    public Excel.Workbook book;    //
    public Excel._Worksheet sheet; //= book.Sheets["XML Inputs"];
    public Excel.Range range;      // = sheet.UsedRange;

    public Sheets()
    {
        app = new Excel.Application();
        book = app.Workbooks.Open(@"C:\dev\Development\Joseph\Projects\PTAC XML File\PTAC XML File\Excel Read FIle 3.0.xlsx");
        sheet = book.Sheets["XML Inputs"];
        range = sheet.UsedRange;

        int rowcount = range.Rows.Count;
        int columncount = range.Columns.Count;

        int i = 0;

    }

    public void Output()
    {

        Excel.Range fastrange1 = (Excel.Range)sheet.Cells[12, 1]; //fetch the number of columns for row 12


        for (int i = 12; i == 12; i++)                            //given row 12, count the number of coulmns
        {

            int fastrange = range.Columns.Count;
            Console.WriteLine(fastrange);
        }

}

2 个答案:

答案 0 :(得分:0)

你可以尝试:

Sheet.UsedRange.Columns.Count

但请注意,根据工作表的编辑历史记录,这可能会比您预期的更多。意思是说用户输入数据直到Z列,表单被保存,然后Z中的数据(不是列)被删除,它可能仍然被认为是UsedRange的一部分,直到整个列被删除为止。下面是一个示例,我们在PowerShell脚本中使用它(在.net中应该是相同的)来压缩工作表(清理我描述的实例)。它不是最有效的代码,但它可以工作。

# attach to excel object
$objExcel = [System.Runtime.InteropServices.Marshal]::GetActiveObject("Excel.Application");

$book = $objExcel.ActiveWorkbook
$shtCount = $book.Sheets.Count
Write-Host $shtCount

for($i = 1; $i -le $shtCount; $i++){
    $sht = $book.Worksheets.item($i)
    $sht.Activate();
    $sht.UsedRange.Select();
    $rows = $sht.UsedRange.Rows.Count;
    $columns = $sht.UsedRange.Columns.Count;
    Write-Host $sht.UsedRange.Address();
    Write-Host "Rows: $rows"
    Write-Host "Columns: $columns"
    #remove blank columns
    for($c = $columns; $c -ge 1; $c--){
        $hasData = 0;
        for($r = 1; $r -le $rows; $r++){
            $cell = $sht.Cells.Item($r, $c);
            if($cell.Text -ne ""){ 
                $hasData = 1;
                break; 
            }
        }
        if($hasData){ 
            Write-Host "Column $c Has Data";
        } else{
            Write-Host "Column $c Has No Data";
            $cell.EntireColumn.Delete();
        }
    }#end for columns
    #remove blank rows
    for($r = $rows; $r -ge 1; $r--){
        $hasData = 0;
        for($c = 1; $c -le $columns; $c++){
            $cell = $sht.Cells.Item($r, $c);
            if($cell.Text -ne ""){ 
                $hasData = 1;
                break; 
            }
        }
        if($hasData){ 
            Write-Host "Row $r Has Data";
        } else{
            Write-Host "Row $r Has No Data";
            $cell.EntireRow.Delete();
        }
    }#end for rows
}#end for sheets

#clean up com objects
[void][System.Runtime.Interopservices.Marshal]::FinalReleaseComObject($cell)
[void][System.Runtime.Interopservices.Marshal]::FinalReleaseComObject($sht)
[void][System.Runtime.Interopservices.Marshal]::FinalReleaseComObject($book)
[void][System.Runtime.Interopservices.Marshal]::FinalReleaseComObject($objExcel)

编辑:根据评论,这里有一些丑陋的代码:

int maxCol = 0;
int columns = sheet.UsedRange.Columns.Count;
Range fastRange = sheet.get_Range("R12C1", "R12C" + columns); //Gets row 12 to used Range
foreach(Range r in fastRange){
    if(!(String.IsNullOrEmpty(r.Text)) && r.Column > maxCol) maxCol = r.Column;
}
Console.WriteLine("Max column for row 12 is: " + maxCol);

我正在做这件事,我认为方法调用是有效的。您可以使用RxCx行列命名格式来获取单元格。如果您想使用get_Range("R12C3", Type.Missing)单个单元格。希望上面的内容能让你开始。用过的电池的测试取决于您(可能有很多选择)。

答案 1 :(得分:0)

我个人使用名为EPPlus的NuGet包。第一步是找到您的Excel文档,然后遍历列和行......

//Get file path
var excelFile = new FileInfo("your-path-here");

//Open file using epplus
using(var package = new ExcelPackage(excelFile))
{
    ExcelWorkbook wkbk = package.Workbook;

    //Make sure file is not empty
    if(wkbk != null)
    {
        if(wkbk.Worksheets.Count > 0)
        {
            //Get the first worksheet
            ExcelWorksheet curworksheet = wkbk.Worksheets.First();

            //Get row count
            var row = curworksheet.Dimension.End.Row;
            //Get column count
            var col = curworksheet.Dimension.End.Column;

            //Cycle through rows
            foreach(int i = 2; i <= row; i++)
            {
                //Cycle through columns for current row
                foreach(int = 1; i <= col; i++)
                {
                    //for each col do something...
                }
            }
        }
    }

}

希望这有帮助。