Number looping get row number(01,02,03) - c#

string[] SName = Request.Form.GetValues("Description");
string[] Email = Request.Form.GetValues("Email");
DataTable dtable = dt();
for (int i = 0; i <= SName.Length - 1; i++)
{
DataRow row1 = dtable.NewRow();
row1["Description"] = SName[i];
row1["Email"] = Email[i];
DAL.DMSS insertdata = new DMSS();
insertdata.INSERT_DATA(loggeduser.SUBSIDIARY_CD, input, SName[i], Email[i]);
}
above are my code to get the data from dynamic row add.
if i have 2 rows,data i get is :
now i want to add 1 more data ,sequence number
tried this code but not working..
for (int i = 0; i <= SName.Length - 1; i++)
{
if (i.length <2 )
{
string strvalue = i.PadLeft(2, '0');
}
else
{
string strvalue = i;
}
DataRow row1 = dtable.NewRow();
row1["Description"] = SName[i];
row1["Email"] = Email[i];
DAL.DMSS insertdata = new DMSS();
insertdata.INSERT_DATA(loggeduser.SUBSIDIARY_CD, input, SName[i], Email[i], strvalue);
}

for (int i = 0; i <= SName.Length - 1; i++)
{
var rowNumber = (i + 1).ToString("0#");
}

Related

Upload Excel file whose column data is dateTime but C# could not figure out NPOI

My Excel has column data like
When I get the data in my asp.net api using below code, I get the data 01-1月-2021 instead of 2021-01-01 then I get the error in line entity.startTime = Convert.ToDateTime(row[0].ToString().Trim());
for (int j = 0; j < HttpContext.Current.Request.Files.Count; j++)
{
string fileName = HttpContext.Current.Request.Files[j].FileName;
if (fileName.Contains(".xlsx") || fileName.Contains(".xls"))
{
dataset = ExcelHelper.ExcelStreamToDataSet(HttpContext.Current.Request.Files[j].InputStream, HttpContext.Current.Request.Files[j].FileName);
bool isFileFind = false;
List<ExcelRowErrorInfoAssetInfo> fileErrorAllList = new List<ExcelRowErrorInfoAssetInfo>();
for (int i = 0; i < dataset.Tables.Count; i++)
{
DataTable table = dataset.Tables[i];
string sheetName = table.TableName;
#region
for (int r = 0; r < table.Rows.Count; r++)
{
DataRow row = table.Rows[r];
int cnt = row.ItemArray.ToList().Where(a => string.IsNullOrEmpty(a.ToString())).Count();
if (cnt < row.ItemArray.Count())
{
if (sheetName == "基本信息")
{
AssetsInfoMap entity = new AssetsInfoMap();
//startTime is type of DateTime
entity.startTime = Convert.ToDateTime(row[0].ToString().Trim());
entity.endTime = Convert.ToDateTime(row[1].ToString().Trim());
}
}
}
#endregion
}
public static DataSet ExcelStreamToDataSet(Stream stream, string fileName)
{
DataSet dataset = new DataSet();
int startRow = 0;
try
{
IWorkbook workbook = null;
if (fileName.IndexOf(".xlsx") > 0)
workbook = new XSSFWorkbook(stream);
else if (fileName.IndexOf(".xls") > 0)
workbook = new HSSFWorkbook(stream);
int sheetCount=workbook.NumberOfSheets;
for (int m = 0; m < sheetCount-1; m++)
{
DataTable data = new DataTable();
ISheet sheet = workbook.GetSheetAt(m);
data.TableName= sheet.SheetName;
if (sheet != null)
{
IRow firstRow = sheet.GetRow(0);
int cellCount = firstRow.LastCellNum;
for (int k = firstRow.FirstCellNum; k < cellCount; ++k)
{
ICell cell = firstRow.GetCell(k);
if (cell != null)
{
string cellValue = cell.StringCellValue;
if (cellValue != null)
{
DataColumn column = new DataColumn(cellValue);
data.Columns.Add(column);
}
}
}
startRow = sheet.FirstRowNum + 1;
int rowCount = sheet.LastRowNum;
for (int i = startRow; i <= rowCount; ++i)
{
IRow row = sheet.GetRow(i);
if (row == null) continue;
DataRow dataRow = data.NewRow();
for (int j = row.FirstCellNum; j < cellCount; ++j)
{
if (row.GetCell(j) != null)
dataRow[j] = row.GetCell(j).ToString();
}
data.Rows.Add(dataRow);
}
}
dataset.Tables.Add(data);
}
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
}
return dataset;
}
}
So how to get correct data to assign it to my model, do you have any ideas based on my above code?
ICell defines a property .DateCellValue, so you should use this when mapping your date values:
ICell cell = row.GetCell(j);
if (cell.CellType == CellType.Numeric && DateUtil.IsCellDateFormatted(cell))
{
dataRow[j] = cell.DateCellValue;
}
This will now store your value as a DateTime rather than as a string. We now need to do away with your DateTime->string->DateTime conversion:
entity.startTime = (DateTime)row[0];

Adding array into datatable with limited columns

I already know how to add array into datatable.
string[] months = {"Jan" , "Feb" , "Mar" , "Apr" , "Jun"};
DataTable dt = new DataTable();
dt.Columns.Add("M1");
dt.Columns.Add("M2");
dt.Columns.Add("M3");
dt.Columns.Add("M4");
dt.Columns.Add("M5");
DataRow row = dt.NewRow();
for (int i = 0; i < months.Length; i++)
{
row[i] = months[i];
}
dt.Rows.Add(row);
The above code perfectly works. But I have a different question. Lets assume I have an array of 8 values.
string[] arr = {"1","2","3","4","5","6","7","8"};
Now I have created a new datatable with 4 columns.
DataTable dt = new DataTable();
dt.Columns.Add("v1");
dt.Columns.Add("v2");
dt.Columns.Add("v3");
dt.Columns.Add("v4");
DataRow row = dt.NewRow();
Now I want to add the values of array in to columns like
arr[0] = v1
arr[1] = v2
arr[2] = v3
arr[3] = v4
arr[4] = v1
arr[5] = v2
arr[6] = v3
arr[7] = v4
Update 1
I have a function in which I want to perform all these actions
public string LoadAMIReadings(string startTS, string endTS, string batch, string divCode, string cc_code)
{
totalRec = 0;
processedRec = 0;
this.BATCH = batch;
this.DIVCODE = divCode;
this.CCCODE = cc_code;
this.FROMDATE = startTS;
this.TODATE = endTS;
HESservicesDoCommandRequest obj = new HESservicesDoCommandRequest();
DataTable dt = new DataTable();
dt.Columns.Add("Application_No", typeof(string));
dt.Columns.Add("REF_NO", typeof(string));
dt.Columns.Add("METER_SERIAL_NO", typeof(string));
dt.Columns.Add("XMETER_NO", typeof(string));
// here I want to call the modified solution
int rowCount = bill.Length / dt.Columns.Count; // array bill is declared globally with 7780 values in it
for (int rowIndex = 0; rowIndex < rowCount; rowIndex++)
{
DataRow row = dt.NewRow();
for (int columnIndex = 0; columnIndex < dt.Columns.Count; columnIndex++)
{
// In case of 2 rows:
// row 1: (0 * 4) + 0 = 0
// row 1: (0 * 4) + 1 = 1
// row 1: (0 * 4) + 2 = 2
// row 1: (0 * 4) + 3 = 3
// row 2: (1 * 4) + 0 = 4
// row 2: (1 * 4) + 1 = 5
// row 2: (1 * 4) + 2 = 6
// row 2: (1 * 4) + 3 = 7
row[columnIndex] = bill[(rowIndex * dt.Columns.Count) + columnIndex];
}
dt.Rows.Add(row);
}
if (dt != null && dt.Rows.Count > 0)
{
totalRec = dt.Rows.Count;
string ReqEnvPath = System.Configuration.ConfigurationManager.AppSettings["ReadEnvPath"].ToString();
XElement SoapReqEnv = XElement.Load(ReqEnvPath);
foreach (DataRow dr in dt.Rows)
{
string uniqueID = dr["APPLICATION_NO"].ToString();
string meterNo = dr["METER_SERIAL_NO"].ToString();
string timestamp = DateTime.UtcNow.ToString("o");
StringBuilder sbArg0 = new StringBuilder();
try
{
sbArg0.AppendFormat(#"<?xml version=""1.0"" encoding=""UTF-8"" ?> " + SoapReqEnv.ToString(), uniqueID, startTS, endTS, timestamp, this.HEXURL, this.HEXUID, this.HEXPWD);
Guid currentGuid = Guid.NewGuid();
obj.getResponseAsync(sbArg0.ToString(), currentGuid + "$" + uniqueID);
obj.getResponseCompleted += this.myHandler;
string delayMS = System.Configuration.ConfigurationManager.AppSettings["DelayMS"].ToString();
ushort delay = 1000;
ushort.TryParse(delayMS, out delay);
System.Threading.Thread.Sleep(delay);
}
catch (Exception ex)
{
error += "Error for UniqID:" + uniqueID + "Desc:" + ex.Message + "\n";
}
finally
{
//System.Threading.Thread.CurrentThread.Join();
}
}
}
return error;
}
How can I add them?
Solution 1
Code example; this is not the best or shortest implemention, but it is a clear and understandable one for novice programmers.
string[] arr = { "1", "2", "3", "4", "5", "6", "7" };
int rowCount = arr.Length / dt.Columns.Count;
for (int rowIndex = 0; rowIndex < rowCount; rowIndex++)
{
DataRow row = dt.NewRow();
for (int columnIndex = 0; columnIndex < dt.Columns.Count; columnIndex++)
{
// In case of 2 rows:
// row 1: (0 * 4) + 0 = 0
// row 1: (0 * 4) + 1 = 1
// row 1: (0 * 4) + 2 = 2
// row 1: (0 * 4) + 3 = 3
// row 2: (1 * 4) + 0 = 4
// row 2: (1 * 4) + 1 = 5
// row 2: (1 * 4) + 2 = 6
// row 2: (1 * 4) + 3 = 7
row[columnIndex] = arr[(rowIndex * dt.Columns.Count) + columnIndex];
}
dt.Rows.Add(row);
}
Solution 2
A more advanced and edge-case-safe solution which uses extension methods to split the original array to multiple sub-arrays and fill a datatable.
public static class Extensions
{
public static IEnumerable<IEnumerable<T>> Split<T>(this T[] array, int size)
{
for (var i = 0; i < (float)array.Length / size; i++)
{
yield return array.Skip(i * size).Take(size);
}
}
public static void FillDataTable<T>(this DataTable dataTable, T[] input)
{
IEnumerable<IEnumerable<T>> rowValues = input.Split(dataTable.Columns.Count);
foreach (IEnumerable<T> rowValue in rowValues)
{
DataRow row = dataTable.NewRow();
T[] cellValues = rowValue.ToArray();
for (int columnIndex = 0; columnIndex < cellValues.Length; columnIndex++)
{
// 'Safe'-check in case the original array didn't contain enough values. The cell value will remain 'null'
if (columnIndex < dataTable.Columns.Count)
{
row[columnIndex] = cellValues[columnIndex];
}
}
dataTable.Rows.Add(row);
}
}
}
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
int[] input = { 1, 2, 3, 4, 5, 6, 7, 8 };
DataTable dataTable = new DataTable();
dataTable.Columns.Add("v1");
dataTable.Columns.Add("v2");
dataTable.Columns.Add("v3");
dataTable.Columns.Add("v4");
dataTable.FillDataTable(input);
}
}
What I mean is that you can do something like this:
DataRow row = null;
for (int i = 0; i < arr.Length; i++) {
if (i % 4 == 0)
{
row = dt.NewRow();
dt.Rows.Add(row);
}
row[i % 4] = arr[i];
}
EDIT: Take this as an example:
var arr = Enumerable.Range(1, 40).ToArray();
for (int i = 0; i < arr.Length; i++)
{
if (i % 4 == 0) { Console.WriteLine("new row"); }
Console.WriteLine($"row[{i % 4}] = arr[{i}];");
}
The output would be:
new row
row[0] = arr[0];
row[1] = arr[1];
row[2] = arr[2];
row[3] = arr[3];
new row
row[0] = arr[4];
row[1] = arr[5];
row[2] = arr[6];
row[3] = arr[7];
new row
row[0] = arr[8];
row[1] = arr[9];
row[2] = arr[10];
row[3] = arr[11];
new row
row[0] = arr[12];
row[1] = arr[13];
row[2] = arr[14];
row[3] = arr[15];
...
Which is what you want, right?
This worked for me, need to add hooks for the edge cases but the concept is simple enough.
string[] arr = { "1", "2", "3", "4", "5", "6", "7", "8" };
DataTable dt = new DataTable();
dt.Columns.Add("v1");
dt.Columns.Add("v2");
dt.Columns.Add("v3");
dt.Columns.Add("v4");
DataRow row = dt.NewRow();
int col = 0;
foreach (var val in arr)
{
if (col > 3)
{
col = 0;
dt.Rows.Add(row);
row = dt.NewRow();
row[col] = val;
}
else
{
row[col] = val;
col++;
}
}
dt.Rows.Add(row);

C# EPPlus not evaluating formula SUM(A3:B3)

I have just started working with EPPlus. i have data table which has some numeric data and formula. when i load data table by EPPlus and save to excel then formula not evaluated i found when i open the same excel file. formula lies in excel cell as string like SUM(A3:B3)
To evaluate formulate i have tried many options of EPPLUS and those are listed here
pack.Workbook.Worksheets["Test"].Calculate();
pack.Workbook.Worksheets["Test"].Cells["A3"].Calculate();
pack.Workbook.Worksheets["Test"].Cells["B3"].Calculate();
ws.Calculate();
Here i am referring my full sample code where formula not working. please have a look and tell me what i need to add in my code to evaluate formula.
private void button1_Click(object sender, EventArgs e)
{
DataTable dt = GetDataTable();
string path = #"d:\EPPLUS_DT_Excel.xlsx";
Stream stream = File.Create(path);
using (ExcelPackage pack = new ExcelPackage())
{
ExcelWorksheet ws = pack.Workbook.Worksheets.Add("Test");
ws.Cells["A1"].LoadFromDataTable(dt, false);
//pack.Workbook.Worksheets["Test"].Calculate();
//pack.Workbook.Worksheets["Test"].Cells["A3"].Calculate();
//pack.Workbook.Worksheets["Test"].Cells["B3"].Calculate();
ws.Calculate();
pack.SaveAs(stream);
stream.Close();
MessageBox.Show("Done");
}
}
public DataTable GetDataTable()
{
string strSum = "", strColName, strImmediateOneUp = "", strImmediateTwoUp = "";
int startsum = 0;
int currow = 0;
bool firstTimeSum = true;
int NumRows = 3;
int NumColumns = 2;
DataTable dt = new DataTable();
for (int col = 0; col < NumColumns; col++)
{
strColName = GenerateColumnText(col);
DataColumn datacol = new DataColumn(strColName, typeof(object));
dt.Columns.Add(datacol);
}
for (int row = 0; row < NumRows; row++)
{
dt.Rows.Add();
for (int col = 0; col < NumColumns; col++)
{
if (row < 2)
{
dt.Rows[row][col] = Convert.ToInt32(new Random().Next(1, NumRows));
}
else
{
if (firstTimeSum)
{
if (row - currow == 2)
{
currow = row;
startsum = 0;
firstTimeSum = false;
}
else
{
startsum = 1;
}
}
else
{
if (row - currow == 3)
{
currow = row;
startsum = 0;
}
}
if (startsum == 0)
{
strColName = GenerateColumnText(col);
strImmediateOneUp = strColName + ((row + 1) - 1).ToString();
strImmediateTwoUp = strColName + ((row + 1) - 2).ToString();
strSum = string.Format("+SUM({0}:{1})", strImmediateTwoUp, strImmediateOneUp);
dt.Rows[row][col] = strSum;
}
else
{
dt.Rows[row][col] = Convert.ToInt32(new Random().Next(1, NumRows));
}
}
}
startsum = 1;
}
return dt;
}
private string GenerateColumnText(int num)
{
string str = "";
char achar;
int mod;
while (true)
{
mod = (num % 26) + 65;
num = (int)(num / 26);
achar = (char)mod;
str = achar + str;
if (num > 0) num--;
else if (num == 0) break;
}
return str;
}
When adding a formula to a cell you use the Formula property. When you load a range from a DataTable using LoadFromDataTable it has no way of knowing that some of the values are meant to be interpreted as formulas.
You can use LoadDataTable to populate the cells on which the formulas will operate, but for the formulas you'll need to set the Formula property.

how to add rows in dynamically in generated columns horizontly

Ihave to add rows in:
dtbl = new DataTable();
dtbl.Columns.Add("Ad.No", typeof(String)); alignment[0] = 'C'; width[1] = 40;
dtbl.Columns.Add("AdmissionDate", typeof(String)); alignment[1] = 'C'; width[2] = 50;
dtbl.Columns.Add("Name", typeof(String)); alignment[2] = 'L'; width[3] = 100;
dtbl.Columns.Add("Class", typeof(String)); alignment[3] = 'C'; width[5] = 40;
for (int i = model.FromYear; i <= model.ToYear; i++)
{
for (int j = model.FromMonth; j <= model.ToMonth; j++)
{
for (int k = model.FromDay; k <= model.ToDay; k++)
{
dtbl.Columns.Add(Common.CommonUtility.GetShortMonthName(j)+" "+k, typeof(String)); alignment[4] = 'C'; width[5] = 40;
}
}
for (int i = model.FromYear; i <= model.ToYear; i++)
{
for (int j = model.FromMonth; j <= model.ToMonth; j++)
{
for (int k = model.FromDay; k <= model.ToDay; k++)
{
// dtbl.Rows.Add(dt[j]=std.value);
// foreach (var r in std.value){
dtbl.Rows.Add(dt["Ad.No"] = std.AdmissionNo, dt["AdmissionDate"] = Convert.ToDateTime(std.date.ToString()).ToString("dd/MM/yyyy"), dt["Class"] = std.Class, dt["Name"] = std.StudentName,dt[j]=std.value);
}
}
I have to add rows in columns cell like p A p A
When creating the columns, the column name could contain also the year to be unique:
private GetColumnName(int year, int month, int day)
{
return year.ToString() + " " + Common.CommonUtility.GetShortMonthName(month) + " " + day;
}
If std contains the value for one date, it would help if the std record provided also this date (or three properties year, month, day).
Then a list of std loaded from DB could be grouped by row identifier (is it the Ad.No?) and each group processed to fill one row:
var stdList = ... select from DB;
var stdGroups = stdList.GroupBy(x => x.AdmissionNo);
foreach(var group in stdGroups)
{
var stds = group.ToList();
var row = dtbl.NewRow(); // a new row of untyped data table
row["Ad.No"] = stds.First().AdmissionNo;
// ...set also the other properties
for (int i = model.FromYear; i <= model.ToYear; i++)
{
for (int j = model.FromMonth; j <= model.ToMonth; j++)
{
for (int k = model.FromDay; k <= model.ToDay; k++)
{
var std = stds.Single(x => x.Year == i && x.Month == j && x.Day == k);
row[GetColumnName(i,j,k)] = std.value;
}
}
}
dtbl.Rows.Add(row);
}

How to compare the rows in a datatable and manipulate itto show in a particular format in C#/asp.net

I have a data in data table with say 4 columns.Out of those 10 columns first column contains the date.The data in the table is in the form :
I/p
"15/12/2010",username,24,No
"16/12/2010",username,24,No
"17/12/2010",username,24,No
"18/12/2010",username,24,No
"19/12/2010",username,24,No
"20/12/2010",username,25,No
"21/12/2010",username,24,yes
"22/12/2010",username,24,No
"23/12/2010",username,24,No
"24/12/2010",username,24,No
"25/12/2010",username,24,No
"26/12/2010",Prakhar,24,No
"27/12/2010",username,24,No
"28/12/2010",username,24,No
We have to bind the o/p with the repeater.
For aforemenioned i/p the output should be :
O/P
"15/12/2010 - 20/12/2010",username,24,No
"21/12/2010 - 21/12/2010",username,24,Yes
"22/12/2010 - 25/12/2010",username,24,no
"26/12/2010 - 26/12/2010",username,24,no
"27/12/2010 - 28/12/2010",username,24,no
I.e. we are clubbing all the dates whose corresponsing column values are matching.
We have to write a c# code for it.
First I have created a new Datatable for our final result:
DataTable dtInventoryTable = new dtInventoryTable();
dtInventoryTable.Columns.Add("RateDate", typeof(string));
dtInventoryTable.Columns.Add("RatePlanId", typeof(string));
dtInventoryTable.Columns.Add("RoomTypeId", typeof(string));
private DataTable DisplayInventoryDetails(DataTable dtInventoryDetail)
{
for (int i = 0; i < dtInventoryDetail.Rows.Count; i++)
{
String[] row = new String[dtInventoryDetail.Columns.Count];
String[] row1 = new String[dtInventoryDetail.Columns.Count];
string str=string.Empty;
int h=0;
str = dtInventoryDetail.Rows[i][0].ToString() + " - " +dtInventoryDetail.Rows[i]0].ToString();
for (int j = i+1;j< dtInventoryDetail.Rows.Count; j++)
{
for (int x = 1; x < dtInventoryDetail.Columns.Count; x++)
{
row[x] = dtInventoryDetail.Rows[i][x].ToString();
}
for (int y = 1; y < dtInventoryDetail.Columns.Count; y++)
{
row1[y] = dtInventoryDetail.Rows[j][y].ToString();
}
bool result = ArraysEqual(row, row1);
if (!result)
{
dtInventoryTable = GetRoomRateTable(row, str);
i = j-1;
h = j;
break;
}
else
str= dtInventoryDetail.Rows[i][0].ToString() + " - " + dtInventoryDetail.Rows[j][0].ToString();
h = j;
}
}
if (h >= dtInventoryDetail.Rows.Count-1)
{
dtInventoryTable = GetRoomRateTable(row, str);
break;
}
}
return dtInventoryTable;
}
private DataTable GetRoomRateTable(String[] row,string str)
{
row[0] = str;
dtInventoryTable.LoadDataRow(row, true);
return dtInventoryTable;
}

Categories

Resources