首页 > 解决方案 > C# Excel - 仅读取/选择具有值/数据的单元格

问题描述

如何读取 excel 文件并仅选择那些具有数据的单元格 - 没有格式,没有空格,只有文本或数字。

我知道我可以像这样阅读电子表格:如何仅在这些单元格上进行“选择”并制作副本。提前致谢

Excel.Application excelApp = new Excel.Application();
    if (excelApp != null)
    {
        Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(@"C:\test.xls", 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
        Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelWorkbook.Sheets[1];

        Excel.Range excelRange = excelWorksheet.UsedRange;
        int rowCount = excelRange.Rows.Count;
        int colCount = excelRange.Columns.Count;

        for (int i = 1; i <= rowCount; i++)
        {
            for (int j = 1; j <= colCount; j++)
            {
                Excel.Range range = (excelWorksheet.Cells[i, 1] as Excel.Range);
                string cellValue = range.Value.ToString();

                //do anything
            }
        }

        excelWorkbook.Close();
        excelApp.Quit();

标签: c#excel

解决方案


使用您现有的方法,您缺少的是将值与 string.empty 进行比较,并知道您可以使用 Excel.Application.Union 来组合范围。

考虑这个伪代码(也就是我没有运行它。)

请注意,如果您想要精确(比向用户显示的 excel 格式更多),您应该使用 .Value2 而不是 .Value。

public void CopyValues()
        {
            Excel.Application excelApp = new Excel.Application();
            if (excelApp != null)
            {
                Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(@"C:\test.xls", 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
                Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelWorkbook.Sheets[1];

                Excel.Range excelRange = excelWorksheet.UsedRange;
                int rowCount = excelRange.Rows.Count;
                int colCount = excelRange.Columns.Count;

                Excel.Range copyRange = null;

                for (int i = 1; i <= rowCount; i++)
                {
                    for (int j = 1; j <= colCount; j++)
                    {
                        Excel.Range range = (excelWorksheet.Cells[i, j] as Excel.Range);
                        if (range.Value.ToString().Trim() != string.Empty)
                        {
                            if (copyRange == null)
                            {
                                copyRange = range;
                            }
                            else
                            {
                                //Its got somehting so union it in
                                copyRange = excelApp.Union(copyRange, range);
                            }
                        }


                    }
                }
                //Copy to clipboard
                copyRange.Copy();

                excelWorkbook.Close();
                excelApp.Quit();
            }
        }

推荐阅读