2016-06-21 74 views
1

所以我的程序需要两种文件类型,.csv和.xlsx。 我有2个方法来检查文件中的数据是否有效。如果文件被验证,它只是返回true如何修改csv和excel工作簿并保存到相同的文件中?

否则,除了返回false,我想添加一个额外的列调用它 “错误”,我想写入到单元格的特定错误消息。

例如,

如果Data.csv原本看起来喜欢这个 第一行是列名-G

A | B | C | D | E | F | ģ

行1

行2

行3

....

假设行和列是0索引

如果数据类型是错误的行3列B(单元格[4] [1])和第2行G列(单元格[2] [6]),我想在G之后创建一个名为H的列,并在第2行H列和第3列H列会有什么信息出错。

像这样

A | B | C | D | E | F | G | H |

行1个

行2 B是错误的类型

行3 G是错误的类型

的......

这里是我的方法

我正在使用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; 
    } 

这个验证CSV是验证各行

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); 
} 

回答

2

沿着这些线路的东西应该你的循环内工作

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; 
    } 

的辅助方法。

xlWorksheet.Cells[RowIndex: i, ColumnIndex: 7].Value = "My error message"; 
+1

我试过以上,但是,我没有看到在Excel中所做的任何更改。另外我必须删除ReadOnly:真的 – ygongdev

+0

mmm在玩了很多游戏后,我想我终于找到了它的工作。我认为这个问题是在Excel过程中没有正确关闭或什么的。谢谢! – ygongdev

相关问题