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

前端 未结 3 1787
一生所求
一生所求 2021-02-07 04:05

I\'m writing numbers to an Excel spreadsheet from a DataTable and all of these numbers are 5 digits long with preceding 0s if the number itself is less than 5 digit

3条回答
  •  春和景丽
    2021-02-07 04:29

    //where [1] is column number which you want to make text

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

    //If you want to format a particular column in all sheets in a workbook - use below code. Remove loop for single sheet along with slight changes.

    //path were excel file is kept

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

提交回复
热议问题