2012-07-31 103 views
-1

從數據表中讀取數據並移入記事本csv文件,在c#中,然後返回到電子表格。然而,在電子表格中,某些單元格是空的(通過空值我的意思是具有=「」的值,只是空格和空格的數量可以不同)。在轉移到記事本並返回到電子表格中時,這些值可能會丟失。有沒有辦法區分這些細胞,所以我可以把引號附近,那麼細胞仍然存在?空單元格包含引號

我已經想通了,大多數這個空細胞有data_string文件類型或布爾,此代碼適用於所有data_string

if (fileType == "data_string") 
{ 
    string see = cell.getFormula().ToString(); 
    sw.Write("'" + see + "' "); 
} 
else 
{ 

    string see = cell.getFormula().ToString(); 
    sw.Write(see + " "); 
} 

但是我不希望所有的布爾數據是在引號只是那些是empty.so,到目前爲止,我還

if (fileType == "bool") 
{ 

    if (cell.getFormula().Empty) 
    { 
     sw.Write("'" + cell.getFormula().ToString() + "' "); 
    } 
} 

但是這並不工作作爲真正的細胞是不是空的,有另一種方式圓嗎?

回答

1

然後忽略了一個事實,他們是布爾,只是檢查字段是否爲空,如:

if (cell.getFormula().StartsWith(" ")) 
        { 
         { 
          for (int i = 0; i < cell.getFormula().Length; i++) 
          { 
           if (cell.getFormula()[i] == ' ') 
           { 

            emptyBool.Add(" "); 

           } 
          } 
          string emptyBoolString = string.Join(" ", emptyBool.ToArray()); 
+0

我沒有考慮這樣做。我設法讓它工作 – loles 2012-08-03 14:34:35

0

手動編碼導入和導出分隔函數充滿危險。相反,我會建議您使用專門開發的FileHelpers等第三方庫,以協助處理這些情況。

像FileHelpers這樣的庫允許您用特定屬性來修飾模型,然後使用該庫來完成繁重的工作。下面是從他們的網站的例子: -

型號

[DelimitedRecord(",")] 
public class Customer 
{ 
    public int CustId; 

    public string Name; 

    public decimal Balance; 

    [FieldConverter(ConverterKind.Date, "dd-MM-yyyy")] 
    public DateTime AddedDate; 

} 

分析器類

var engine = new FileHelperEngine(typeof(Customer)); 

// To Read Use: 
Customer[] res = engine.ReadFile("FileIn.txt") as Customer[]; 

// To Write Use: 
engine.WriteFile("FileOut.txt", res); 

注:有不過是做類似的工作,我只用過其他庫FileHelpers並沒有失望。

0
if you are using **bool**, then its a **bit** so it can't be empty, 
it is either true or false or you can use null 
1

您可以檢查單元格長度是否大於0(因此不是空的),如果不是(表示它是空的),則添加您的撇號。我是新來的C#,所以我不知道這是否會工作或沒有

if (fileType == "bool") 
{ 
    if (!cell.getFormula().length > 0) // If the cell is not longer than 0 characters 
    { 
     string see = cell.getFormula().ToString(); 
     sw.Write("'" + see + "' "); 
    } 
    else 
    { 
     string see = cell.getFormula().ToString(); 
     sw.Write(see + " "); 
    } 
+0

不會工作空間仍然算作字符(哦,並刪除帳戶) – loles 2012-08-01 07:06:18

+0

我已修復它(仍在刪除) – loles 2012-08-01 07:46:34

相關問題