首页 > 解决方案 > C# Excel 编程获取特定范围并创建 .csv 文件

问题描述

在此处输入图像描述 你好。我想要实现的是循环遍历最左边的列,直到找到一个非空单元格。当我找到一个时,我想存储所有行,直到我在最左边的列中找到另一个非空单元格。结果必须存储在单独的 .csv 文件中。

参考添加的图片。我想要一个名为 john 的 .csv 文件。在 John.csv 文件中,我想要第 1,2 和 3 行。

并继续这种趋势,直到工作表中没有任何内容。如果您使用图片中的输入,我将有一个 John.csv 文件,其中包含第 1,2 和 3 行,以及一个 komar.csv 文件,其中包含第 4 和第 5 行。

我安静地坚持我如何才能达到这个结果。

标签: c#excel

解决方案


这将做你想要的。只需在单击按钮中添加此行即可启动它(当然,使用您自己的路径和文件名以及工作表名称):

ProcessFile(@"c:\temp\", "book2.xlsx", "sheet1");

并将下面的代码放在一个表单或一个类或任何你想要的地方:

using Excel = Microsoft.Office.Interop.Excel;

    private void ProcessFile(string folderPath, string inputFileName, string inputSheetName)
    {

        string outputFileName = "";//will change for each file

        object[,] data = ReadWorksheetFromExcel(folderPath + inputFileName, inputSheetName);
        StringBuilder sbRow = new StringBuilder();
        string comma = "";
        StringBuilder sbFile = new StringBuilder();

        for (int row = 1; row <= data.GetLength(0); row++)
        {
            if (data[row, 1] != null && data[row, 1].ToString().Trim() != "")
            {
                if (sbFile.ToString() != "")
                {
                    //write previous name to a file
                    System.IO.File.WriteAllText(folderPath + outputFileName, sbFile.ToString());
                }
                //save the value of column 1 to use as the
                //file name once all the data is read for this file
                outputFileName = data[row, 1].ToString().Trim() + ".csv";
                sbFile.Clear();
            }
            for (int col = 2; col <= data.GetLength(1); col++)
            {
                if (data[row, col] != null && data[row, col].ToString() != "")
                {
                    string value = data[row, col].ToString();
                    sbRow.Append(comma + value);
                    comma = ",";
                }
            }
            sbFile.AppendLine(sbRow.ToString());
            sbRow.Clear();
            comma = "";
        }
        if (sbFile.ToString() != "")
        {
            //write final name to a file
            System.IO.File.WriteAllText(folderPath + outputFileName + ".csv", sbFile.ToString());
        }
    }
    public object[,] ReadWorksheetFromExcel(string ExcelFilePath, string WorksheetName)
    {
        var excel = new Excel.Application();
        excel.DisplayAlerts = false;
        excel.Visible = true;

        Excel.Workbook workbook = excel.Workbooks.Open(ExcelFilePath, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
        Excel.Worksheet worksheet = workbook.Worksheets[WorksheetName];

        Excel.Range range = worksheet.UsedRange;
        object[,] values = (object[,])range.Value2;

        return values;
    }

推荐阅读