c# - C# Excel 编程获取特定范围并创建 .csv 文件
问题描述
你好。我想要实现的是循环遍历最左边的列,直到找到一个非空单元格。当我找到一个时,我想存储所有行,直到我在最左边的列中找到另一个非空单元格。结果必须存储在单独的 .csv 文件中。
参考添加的图片。我想要一个名为 john 的 .csv 文件。在 John.csv 文件中,我想要第 1,2 和 3 行。
并继续这种趋势,直到工作表中没有任何内容。如果您使用图片中的输入,我将有一个 John.csv 文件,其中包含第 1,2 和 3 行,以及一个 komar.csv 文件,其中包含第 4 和第 5 行。
我安静地坚持我如何才能达到这个结果。
解决方案
这将做你想要的。只需在单击按钮中添加此行即可启动它(当然,使用您自己的路径和文件名以及工作表名称):
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;
}
推荐阅读
- c++ - 在 opencv dnn 中加载 onnx 模型
- wget - 检索通过 wget 下载的文件路径
- reactjs - React 正确接收道具但变得未定义
- kubernetes - Digitalocean 上任何节点的初始角色主机如何
- oracle - Oracle 全文搜索。在 CATSEARCH 中使用参数
- clips - 剪辑。如何检查是否已经给出了与事实匹配的事实列表?
- ios - 设置偏移量的 SwiftUI 图形问题
- python - 检查将罗马数字转换为整数的特定情况
- css - 如何从源映射中导出所有原始 .scss 文件
- javascript - 最简单的 Express 路线返回 404