programing

C#을 사용하여 마지막으로 채워진 Excel 행을 프로그래밍 방식으로 가져오는 중

lovejava 2023. 4. 19. 21:50

C#을 사용하여 마지막으로 채워진 Excel 행을 프로그래밍 방식으로 가져오는 중

Microsoft.interop을 사용하여 엑셀 시트의 마지막 행을 프로그램적으로 가져오려고 합니다.Excel 라이브러리와 C#.저는 엑셀 스프레드시트의 모든 레코드를 루핑하여 조작을 하고 있기 때문에 그렇게 하고 싶습니다.구체적으로는 마지막 행의 실제 번호가 필요합니다.이 번호는 함수에 넣을 것이기 때문입니다.어떻게 하는지 아는 사람?

몇 가지 방법,

using Excel = Microsoft.Office.Interop.Excel;

Excel.ApplicationClass excel = new Excel.ApplicationClass();
Excel.Application app = excel.Application;
Excel.Range all = app.get_Range("A1:H10", Type.Missing);

또는

Excel.Range last = sheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
Excel.Range range = sheet.get_Range("A1", last);

int lastUsedRow = last.Row;
int lastUsedColumn = last.Column;

이것은 Excel의 일반적인 문제입니다.

다음은 C# 코드입니다.

// Find the last real row
nInLastRow = oSheet.Cells.Find("*",System.Reflection.Missing.Value, 
System.Reflection.Missing.Value, System.Reflection.Missing.Value,    Excel.XlSearchOrder.xlByRows,Excel.XlSearchDirection.xlPrevious, false,System.Reflection.Missing.Value,System.Reflection.Missing.Value).Row;

// Find the last real column
nInLastCol = oSheet.Cells.Find("*", System.Reflection.Missing.Value,     System.Reflection.Missing.Value,System.Reflection.Missing.Value, Excel.XlSearchOrder.xlByColumns,Excel.XlSearchDirection.xlPrevious,    false,System.Reflection.Missing.Value,System.Reflection.Missing.Value).Column;

여기서 찾을 수 있다

또는 사용SpecialCells

Excel.Range last = sheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
Excel.Range range = sheet.get_Range("A1", last);

[편집] 유사한 스레드:

프릭크의 대답은 내게 가장 효과가 있었다.마지막에 조금 넣었어요..Row그래서 그냥 반품하는 게 아니라range단,integer.

int lastRow = wkSheet.Cells.SpecialCells(XlCellType.xlCellTypeLastCell, Type.Missing).Row;

모든 시나리오(Protected sheets 제외):

지원 대상:

  • 숨김 행/열 검색

  • 데이터/수식이 없는 포맷된 셀 무시

코드:

// Unhide All Cells and clear formats
sheet.Columns.ClearFormats();
sheet.Rows.ClearFormats();

// Detect Last used Row - Ignore cells that contains formulas that result in blank values
int lastRowIgnoreFormulas = sheet.Cells.Find(
                "*",
                System.Reflection.Missing.Value,
                InteropExcel.XlFindLookIn.xlValues,
                InteropExcel.XlLookAt.xlWhole,
                InteropExcel.XlSearchOrder.xlByRows,
                InteropExcel.XlSearchDirection.xlPrevious,
                false,
                System.Reflection.Missing.Value,
                System.Reflection.Missing.Value).Row;
// Detect Last Used Column  - Ignore cells that contains formulas that result in blank values
int lastColIgnoreFormulas = sheet.Cells.Find(
                "*",
                System.Reflection.Missing.Value,
                System.Reflection.Missing.Value,
                System.Reflection.Missing.Value,
                InteropExcel.XlSearchOrder.xlByColumns,
                InteropExcel.XlSearchDirection.xlPrevious,
                false,
                System.Reflection.Missing.Value,
                System.Reflection.Missing.Value).Column;

// Detect Last used Row / Column - Including cells that contains formulas that result in blank values
int lastColIncludeFormulas = sheet.UsedRange.Columns.Count;
int lastColIncludeFormulas = sheet.UsedRange.Rows.Count;

Excel 객체 모델에 관한 질문의 경우 VBA에서 먼저 사용해보고 C#으로 번역하는 것이 매우 간단합니다.

이 경우 VBA에서 이를 수행하는 한 가지 방법은 다음과 같습니다.

Worksheet.UsedRange.Row + Worksheet.UsedRange.Rows.Count - 1

ActiveSheet.UsedRange.Value의 2차원 객체 배열을 반환합니다.[row, column]. 양쪽 치수의 길이를 확인하면LastRow인덱스 및LastColumn다음 예에서는 C#을 사용하고 있습니다.

Excel.Worksheet activeSheet;
Excel.Range activeRange;

public virtual object[,] RangeArray 
{
    get { return ActiveRange.Value; }
}

public virtual int ColumnCount 
{
    get { return RangeArray.GetLength(1); }
}

public virtual int RowCount
{
    get { return RangeArray.GetLength(0); }
}

public virtual int LastRow 
{
    get { return RowCount; }
}

이 문제는 빈 셀이 있을 가능성이 있는 경우 더욱 심각합니다.그러나 값이 하나만 채워져도 행을 읽어야 합니다.채워지지 않은 셀이 많으면 시간이 걸릴 수 있지만 입력이 정확에 가까우면 다소 빠릅니다.

이 솔루션은 완전히 비어 있는 행을 무시하고 가장 긴 열의 행 수를 반환합니다.

private static int GetLastRow(Worksheet worksheet)
    {
        int lastUsedRow = 1;
        Range range = worksheet.UsedRange;
        for (int i = 1; i < range.Columns.Count; i++)
        {
            int lastRow = range.Rows.Count;
            for (int j = range.Rows.Count; j > 0; j--)
            {
                if (lastUsedRow < lastRow)
                {
                    lastRow = j;
                    if (!String.IsNullOrWhiteSpace(Convert.ToString((worksheet.Cells[j, i] as Range).Value)))
                    {
                        if (lastUsedRow < lastRow)
                            lastUsedRow = lastRow;
                        if (lastUsedRow == range.Rows.Count)
                            return lastUsedRow - 1;
                        break;
                    }
                }
                else
                    break;
            }
        }
        return lastUsedRow;
    }

Special Cells 메서드(다른 셀은 잘 모르겠습니다)를 사용하는 경우 마지막 셀이 Marge될 경우 Range를 사용하여 마지막 행과 열 번호를 얻을 수 없습니다.행과 범위마지막 행과 열을 숫자로 가져올 열입니다.먼저 범위를 해제하고 다시 마지막 셀을 얻어야 합니다.돈이 많이 들었어요.

private int[] GetLastRowCol(Ex.Worksheet ws)
    {
        Ex.Range last = ws.Cells.SpecialCells(Ex.XlCellType.xlCellTypeLastCell, Type.Missing);
        bool isMerged = (bool)last.MergeCells;
        if (isMerged)
        {
            last.UnMerge();
            last = ws.Cells.SpecialCells(Ex.XlCellType.xlCellTypeLastCell, Type.Missing);
        }
        return new int[2] { last.Row, last.Column };
    }

앞서 설명한 바와 같이 (xlCellTypeLastCell 등)의 기법이 항상 기대되는 결과를 제공하는 것은 아닙니다.값을 확인하는 열을 반복하는 것은 어렵지 않지만 후속 행에 데이터를 포함하는 빈 셀이나 행이 있을 수 있습니다.Excel을 직접 사용하는 경우 마지막 행을 찾는 좋은 방법은 CTRL + 아래쪽 화살표를 여러 번 누른 다음(XLSX 워크시트의 경우 1048576 행으로 표시됨) CTRL + 위쪽 화살표를 눌러 마지막으로 채워진 셀을 선택하는 것입니다.매크로를 기록할 때 Excel에서 이 작업을 수행하면 이를 복제하기 위한 코드를 얻을 수 있습니다.그것은 Microsoft를 사용하여 C#에 맞게 수정하는 경우입니다.Office.Interop.Excel 라이브러리예를 들어 다음과 같습니다.

    private int GetLastRow()
    {
        Excel.Application ExcelApp;
        ExcelApp = new Excel.Application();

        ExcelApp.Selection.End(Excel.XlDirection.xlDown).Select();
        ExcelApp.Selection.End(Excel.XlDirection.xlDown).Select();
        ExcelApp.Selection.End(Excel.XlDirection.xlDown).Select();

        ExcelApp.Selection.End(Excel.XlDirection.xlUp).Select();

        return ExcelApp.ActiveCell.Row;
    }

가장 우아한 솔루션은 아닐 수도 있지만(XlUp을 사용하기 전에 스프레드시트의 마지막 행으로 먼저 이동할 수 있을 것 같습니다). 하지만 신뢰성이 더 높은 것 같습니다.

CtrlDot과 Leo Guardian이 말했듯이 메서드는 그다지 정확하지 않으며 포맷이 "SpecialCells"에 영향을 미치는 파일도 있습니다.

그래서 'While'을 더해서 썼어요.

Range last = sheet.Cells.SpecialCells(XlCellType.xlCellTypeLastCell, Type.Missing);
Range range = sheet.get_Range("A1", last);
int lastrow = last.Row;
// Complement to confirm that the last row is the last
string textCell= "Existe";
while (textCell != null)
{
 lastrow++;
 textCell = sheet.Cells[lastrow + 1, 1].Value;
}
                
                

현재 OfficeOpenXml을 사용하고 있는 경우:

using OfficeOpenXml;
using System.IO;

FileInfo excelFile = new FileInfo(filename);
ExcelPackage package = new ExcelPackage(excelFile);
ExcelWorksheet sheet = package.Workbook.Worksheets[1];
int lastRow = sheet.Dimension.End.Row;
int lastColumn = sheet.Dimension.End.Column;

Microsoft 를 사용하는지 어떤지는 모릅니다.Office.Interop.Excel은 여전히 최첨단 또는 레거시 라이브러리입니다.OfficeOpenXml로 교체하는 것이 좋다고 생각합니다.따라서 이 답변은 향후 검색 결과에 도움이 될 수 있습니다.

언급URL : https://stackoverflow.com/questions/7674573/programmatically-getting-the-last-filled-excel-row-using-c-sharp