Appending = "0xxxx", чтобы превзойти ячейку при экспорте с использованием NPOI для поддержания начального нуля или как установить ячейку как текст - PullRequest
0 голосов
/ 27 ноября 2011

Я пытаюсь поддерживать лидирующие нули при экспорте столбца, содержащего номера телефонов, чтобы преуспеть, используя NPOI в приложении asp.net mvc 3.Я прочитал здесь;http://creativyst.com/Doc/Articles/CSV/CSV01.htm#CSVAndExcel, что я могу добавить = "[некоторое число, начинающееся с 0]", чтобы Excel поддерживал нули.Я также прочитал, что если я установлю ячейку как текст, она будет поддерживать ноль.Я потерпел неудачу в моих попытках сделать это.Вот мой код:

 public ActionResult Export(int page, string orderBy, string filter)
    {
        //Get the data representing the current grid state - page, sort and filter
        GridModel model = Model().ToGridModel(page, 10, orderBy, string.Empty, filter);
        var orders = model.Data.Cast<Advertiser>();

        //Create new Excel workbook
        var workbook = new HSSFWorkbook();


        //Create new Excel sheet
        var sheet = workbook.CreateSheet();


        //(Optional) set the width of the columns
        sheet.SetColumnWidth(0, 10 * 256);
        sheet.SetColumnWidth(1, 50 * 256);
        sheet.SetColumnWidth(2, 50 * 256);
        sheet.SetColumnWidth(3, 50 * 256);

        //Create a header row
        var headerRow = sheet.CreateRow(0);



        //Set the column names in the header row
        headerRow.CreateCell(0).SetCellValue("Name");
        headerRow.CreateCell(1).SetCellValue("Phone");
        headerRow.CreateCell(5).SetCellValue("Company Name");
        headerRow.CreateCell(7).SetCellValue("Address 1");
        headerRow.CreateCell(8).SetCellValue("Address 2");
        headerRow.CreateCell(9).SetCellValue("Address 3");
        headerRow.CreateCell(10).SetCellValue("Address 4");
        headerRow.CreateCell(11).SetCellValue("Post Code");
        headerRow.CreateCell(14).SetCellValue("Email");
        headerRow.CreateCell(16).SetCellValue("Website");
        headerRow.CreateCell(19).SetCellValue("Listing Type");

        //(Optional) freeze the header row so it is not scrolled
        sheet.CreateFreezePane(0, 1, 0, 1);

        int rowNumber = 1;

        //Populate the sheet with values from the grid data
        foreach (Advertiser order in orders)
        {
            //Create a new row
            var row = sheet.CreateRow(rowNumber++);

            //Set values for the cells
            row.CreateCell(0).SetCellValue(order.AdvertiserName);
            row.CreateCell(1).SetCellValue(order.Phone);
            row.CreateCell(3).SetCellValue(order.CompanyName);
            row.CreateCell(5).SetCellValue(order.Address1);
            row.CreateCell(6).SetCellValue(order.Address2);
            row.CreateCell(7).SetCellValue(order.Address3);
            row.CreateCell(8).SetCellValue(order.Address4);
            row.CreateCell(9).SetCellValue(order.Postcode);
            row.CreateCell(10).SetCellValue(order.AdvertiserEmail);
            row.CreateCell(11).SetCellValue(order.Website);
            row.CreateCell(12).SetCellValue(order.listing.type);



        }

        //Write the workbook to a memory stream
        MemoryStream output = new MemoryStream();
        workbook.Write(output);

        //Return the result to the end user

        return File(output.ToArray(),   //The binary data of the XLS file
            "application/vnd.ms-excel", //MIME type of Excel files
            "Advertisers.xls");     //Suggested file name in the "Save as" dialog which will be displayed to the end user
    }
}

Я пробовал метод setCellTyoe в разных местах без удачи.

Я не против того, как это делается, я просто хочу поддерживать ведущие нуликогда лист экспортируется.

Ответы [ 2 ]

1 голос
/ 27 ноября 2011

Я не могу проверить это, но вы пытались установить тип в вызове createCell ?Если все остальное не помогло, вы можете прибегнуть к проверенному и правильному способу поставить одинарную кавычку перед начальным нулем:

'00185

Это приведет к тому, что ячейка станет текстовой, и Excel должен будет отображать ее только при редактировании.

0 голосов
/ 28 ноября 2011

Изменен тип данных со строки на int, и NPOI установил ячейку как текст, оставив ведущий ноль.

...