簡體   English   中英

如何使用C#更改Excel單元格的文本格式?

[英]How can i change the text format of a Excel Cell using C#?

我目前正在編寫一個應用程序(C#),根據其他報告在Excel文件中生成報告。

問題是,一旦從某個工作表中獲取一個數字,並復制到另一個工作表,目標單元格沒有正確格式化,並且該數字無法正確顯示。

E.g : 
Number from source : 14.34 
Number on destination : 14.345661

如何格式化目標單元格以強制數字格式與源單元格相同。

謝謝 !

excel中給定單元格/范圍的格式可以通過代碼設置。

public void SetCustomFormat(string format, int r, int c)
{
    ((Excel.Range)xlWks.Cells[r, c]).NumberFormat = format;
}

在您的具體情況下,我認為您需要使用“#.00”或“#。##”格式

這是我正在使用的一些代碼的片段,向您展示格式化單元格的一般模式。 顯然,有一些變量被聲明,但它應該顯示你需要的東西。

sheet.get_Range("A" + CurrentRowIndex.ToString(), ColPrefix + CurrentRowIndex.ToString()).Font.Bold = true;
sheet.get_Range("A" + CurrentRowIndex.ToString(), ColPrefix + CurrentRowIndex.ToString()).Interior.Color = Color.Silver.ToArgb();
sheet.get_Range("A" + CurrentRowIndex.ToString(), ColPrefix + CurrentRowIndex.ToString()).BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic, null);
sheet.get_Range("A" + CompetencyStartRowIndex.ToString(), ColPrefix + CurrentRowIndex.ToString()).BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic, null);

第一行,假設CurrentRowIndex = 1和ColPrefix =“B”,用結果值替換變量將轉換為

sheet.get_Range("A1", "B1").Font.Bold = true;

無論如何,您要設置數字格式。 (未來..)

sheet.Cells[Row, Column].NumberFormat = "0.00"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM