简体   繁体   中英

How to keep two digits of double digit string in same Excel cell after data table import in C#

I have some C# code automatically generating a datatable and importing it to an excel doc to be emailed to an entered email address via a CSHTML form. One of the columns is an ID column. Although the IDs are integers starting from 1, through the CSHTML form they are coming in as string form elements.

I used the following code for the datatable and excel import.

DataSet ds = new DataSet("Builder_Report");
DataTable dt = new DataTable("Requested_Data");
DataColumn column;
DataRow row;

var rows_ID = Request.Form.Get("ID");

column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "Review ID";
column.AutoIncrement = false;
column.Caption = "Review ID";
column.ReadOnly = false;
column.Unique = false;
dt.Columns.Add(column);

........................

foreach (var ID in rows_ID)
{
    row = dt.NewRow();
    row["Review ID"] = ID;
    ............
    dt.Rows.Add(row);
}
ExcelEngine excelEngine = new ExcelEngine();
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Xlsx;

IWorkbook requested_report = application.Workbooks.Create();

//Creating a Sheet
IWorksheet sheet = requested_report.Worksheets.Create("Requested Details");
sheet.ImportDataTable(dt, true, 1, 1);
sheet.UsedRange.WrapText = true;

For some reason, for every double digit ID number, the two digits get separated into two different rows, eg, for ID number 10, "1" appears in one row under the ID Column and 0 appears in the row below it. I'm not sure why that particular string is getting split. This is the only code I have that affects that particular ID column.

What is the data type of rows_ID if you step through this in the debugger? From your code, it looks like you are expecting it to be an array of strings, but I'm betting it's coming through as just a plain old string. Your foreach loop is then looping over each character in the string.

If you are expecting it to be an array, you should name the form field ID[] and change this:

var rows_ID = Request.Form.Get("ID");

to

var rows_ID = Request.Form.Get("ID[]");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM