簡體   English   中英

C#Excel Interop:如何格式化單元格以將值存儲為文本

[英]C# Excel Interop: How to format cells to store values as text

我正在從DataTable向Excel電子表格中寫入數字,如果數字本身長度小於5位,所有這些數字都是5位數字,前面有0(例如,395將存儲為00395)。

將這些數字輸入Excel(使用C#)時,它將它們存儲為數字並消除前面的0。 有沒有什么辦法可以格式化C#中的單元格,以便將值存儲為文本而不是數字?

你可以SomeRange.NumberFormat = "@"; 或者,如果您在值前加上'並將其寫入單元格,則將excel視為數字存儲為文本並提供視覺提示。

這個答案剛剛解決了我們公司軟件解決方案的一個主要問題,我必須檢索顯示的值,但是一旦我將其設置為新工作表,就會將其作為數字插入。 簡單解決方案 我還不能投票,但是它最終會如何結束。

for (int h = 1; h <= 1; h++)
{
    int col = lastColl(sheets);
    for (int r = 1; r <= src.Count; r++)
    {
        sheets.Cells[r, col + 1] = "'"+src.Cells[r, h].Text.ToString().Trim();
    }
}

//其中[1]是您要創建文本的列號

ExcelWorksheet.Columns[1].NumberFormat = "@";

//如果要格式化工作簿中所有工作表中的特定列,請使用下面的代碼。 刪除單張紙張的循環以及稍作更改。

//路徑是excel文件保存

string ResultsFilePath = @“C:\\ Users \\ krakhil \\ Desktop \\ TGUW EXCEL \\ TEST”;

    Excel.Application ExcelApp = new Excel.Application();
    Excel.Workbook ExcelWorkbook = ExcelApp.Workbooks.Open(ResultsFilePath);
    ExcelApp.Visible = true;

    //Looping through all available sheets
    foreach (Excel.Worksheet ExcelWorksheet in ExcelWorkbook.Sheets)
    {                
        //Selecting the worksheet where we want to perform action
        ExcelWorksheet.Select(Type.Missing);
        ExcelWorksheet.Columns[1].NumberFormat = "@";
    }

    //saving excel file using Interop
    ExcelWorkbook.Save();

    //closing file and releasing resources
    ExcelWorkbook.Close(Type.Missing, Type.Missing, Type.Missing);
    Marshal.FinalReleaseComObject(ExcelWorkbook);
    ExcelApp.Quit();
    Marshal.FinalReleaseComObject(ExcelApp);

暫無
暫無

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

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