如何修改csv和excel工作簿并保存到相同的文件?
所以我的程序需要两种文件types,.csv和.xlsx。 我有两个方法,检查文件内的数据是否validation。 如果文件被validation,它只是返回true
否则,除了返回false,我想添加一个额外的列调用它“错误”,我想写入特定的错误消息到单元格中。
例如,
如果Data.csv最初看起来像这样第一行是列名称AG
A | B | C | D | E | F | G
第1行
第2行
第3行
….
假设行和列是0索引
如果行3列B(单元格[4] [1])和行2列G(单元格[2] [6])中的数据types错误,我想要在G之后创build一个列,并在第2行H和第3行H列,我会得到一个错误信息。
像这样
A | B | C | D | E | F | G | H |
第1行
第2行B是错误的types
第3行G是错误的types
……
这是我的方法
我正在使用Excel Interlop for xlsx
private bool FileValidatorXlsx() { Excel.Application xlApp = new Excel.Application(); Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(_filename, ReadOnly: true); foreach (Excel.Worksheet xlWorksheet in xlWorkbook.Worksheets) { Excel.Range xlRange = xlWorksheet.UsedRange; int rowCount = xlRange.Rows.Count; int colCount = xlRange.Columns.Count; for (int i = 2; i <= rowCount; i++) { string row = ""; for (int j = 1; j <= colCount; j++) { if (xlRange.Cells[i, j].Value2 == null) { return false; } else { // These 2 columns consist of time format (h:mm); if (j == 6 || j == 7) { row += (xlRange.Cells[i, j].Text); } else { row += (string)xlRange.Cells[i, j].Value2.ToString(); } // Don't want to append , to the last item if (j < colCount) { row += ','; } } } // if the record (row) is not valid, just return false if (!ValidateRecord(row)) { return false; } } } return true; }
这个validationcsv
private bool FileValidatorCsv() { string currentLine; using (StreamReader sr = new StreamReader(_filename)) { currentLine = sr.ReadLine(); while ((currentLine = sr.ReadLine()) != null) { if (!ValidateRecord(currentLine)) { return false; } } } return true; }
帮助方法validation单个行
private bool ValidateRecord(string record) { List<string> row; switch (_fileType) { case ((int)extensionTypes.CSV): row = record.Split(',').ToList<string>(); if (row.Count != 9) { return false; } break; case ((int)extensionTypes.XLSX): row = record.Split(',').ToList<string>(); if (row.Count != 9) { return false; } break; default: return false; } return IsValidRow(row); }
沿着这些线的东西应该在你的循环内工作。
xlWorksheet.Cells[RowIndex: i, ColumnIndex: 7].Value = "My error message";