如果我导出一个Excel并导入它(不打开它并单击并保存它),那么Excel中的第二个列在DataTable中是不可读的。
如果我在打开它并单击任何列并保存后导入同一个文件,那么导入Excel就成功了。
int rowNumber = 0;
int cellNo = 0;
//Create new Excel workbook
var workbook = new NPOI.HSSF.UserModel.HSSFWorkbook();
NPOI.SS.UserModel.DataFormat accountingNewFormat = workbook.CreateDataFormat();
CellStyle headerCellStyle = workbook.CreateCellStyle();
headerCellStyle.DataFormat = accountingNewFormat.GetFormat("Text");
//Create new Excel sheet
var sheet = workbook.CreateSheet("Equipment List");
// (Optional) set the width of the columns
sheet.SetColumnWidth(0, 30 * 256);
sheet.SetColumnWidth(1, 20 * 256);
//Create a header row
var headerRow = sheet.CreateRow(rowNumber++);
headerRow.CreateCell(cellNo++).SetCellValue("ColumnName");
headerRow.CreateCell(cellNo++).SetCellValue("ConstantValue");
// cell.CellStyle.DataFormat = accountingNewFormat.GetFormat("General");
// (Optional) freeze the header row so it is not scrolled
sheet.CreateFreezePane(0, 1, 0, 1);
// Populate the sheet with values from the grid data
for (int x = 0; x < 2;x++ )
{
cellNo = 0;
// Create a new row
var row = sheet.CreateRow(rowNumber++);
row.CreateCell(cellNo++).SetCellValue("raj"+x);
row.CreateCell(cellNo).SetCellValue("123");
}
//Write the workbook to a memory stream
System.IO.MemoryStream output = new System.IO.MemoryStream();
workbook.Write(output); //Return the result to the end user
//File(output.ToArray(), //The binary data of the XLS file
// "application/vnd.ms-excel",
// //MIME type of Excel files
// "EquipmentList_" + DateTime.Now.ToString("dd/MM/yyyy hh:mm") + ".xls");
////Suggested file name in the "Save as" dialog which will be displayed to the end user
System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response;
Response.ContentType = "application/vnd.ms-excel";
//Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", HttpContext.Current.Server.MapPath("~/MasterPDF/" + filename)));
Response.AppendHeader("Content-disposition", "attachment; filename=" + "rajdeep_TempFile.xls");
Response.Clear();
Response.BinaryWrite(WriteToStream_constant(workbook).GetBuffer());
Response.End();