how to add rows in dynamically in generated columns horizontly - c#

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

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

Number looping get row number(01,02,03)

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#");
}

c# parallel.for gaussian elimination

I am trying to solve Gaussian elimination in c# using parallel-processing (in this case Parallel.For). My code is sometimes running fine and sometimes not.
I used as a starting point the code shown on the link: http://www.codeproject.com/Tips/388179/Linear-Equation-Solver-Gaussian-Elimination-Csharp .
I didn't use Parallel.For for back insertion just yet because there is problem with elimination.
Elimination Class:
public static bool Gauss(double[][] M)
{
int rowCount = (M.GetLength(0));
int temp = rowCount - 1;
//elimination
Parallel.For(0, temp, sourceRow =>
//for (int sourceRow = 0; sourceRow + 1 < rowCount; sourceRow++)//diagonal
{
for (int destRow = sourceRow + 1; destRow < rowCount; destRow++)//destination row
{
double df = M[sourceRow][sourceRow];
double sf = M[destRow][sourceRow];
for (int j = 0; j < rowCount + 1; j++) // line
{
M[destRow][j] = (M[destRow][j] * df - M[sourceRow][j] * sf) / df;
}
}
});
//back-insertion
for (int row = rowCount - 1; row >= 0; row--)
{
double f = M[row][row];
if (f == 0) return false;
for (int i = 0; i < rowCount + 1; i++) M[row][i] /= f;
for (int destRow = 0; destRow < row; destRow++)
{
M[destRow][rowCount] -= M[destRow][row] * M[row][rowCount];
M[destRow][row] = 0;
}
}
return true;
}
Generate Array:
public static double[][] GenerateArray2(int n)
{
Random rnd = new Random();
double[][] M = new double[n][];
for (int i = 0; i < n; i++)
{
M[i] = new double[n + 1]; // Create inner array
for (int j = 0; j < n + 1; j++)
M[i][j] = rnd.Next(-20, 20);
}
return M;
}
Print Array
public static string Print2(double[][] M)
{
string str = "";
int rowCount = M.GetUpperBound(0) + 1;
for (int row = 0; row < rowCount; row++)
{
for (int i = 0; i <= rowCount; i++)
{
str += M[row][i];
str += "\t";
}
str += Environment.NewLine;
}
return str;
}
Results are wrong in matrix 16x17 and up. At this point I don't know how to continue, I tried to lock M in elimination, didn't help.
Thanks for any help.

Microsoft Solver Foundation doesn't solve what is solved by Excel solver

I have a non-linear optimization problem with constraints. I solved it with Excel Solver (GRG)
but when I tried to translate it to C# with Microsoft Solver Foundation it gets solution.Quality = SolverQuality.Unknown.
The problem is this: I have some decisions and limit constraints (upper and lower) for every one of them. And two other constraints (this ones are the problematic constraints):
the sum of the Decision need to be 1 (100%)
(MMULT(TRANSPOSE(Decision-Array),MMULT(Tabel-with-values,Decision-Array)))^0.5 needs to be equal to another value
The goal is sum(Decision * value). I write it by Microsoft Solver Foundation like this:
SolverContext solverData = SolverContext.GetContext();
context.ClearModel();
model = context.CreateModel();
for (i=0 ; i< decisionCount; i++)
{
var decision = new Decision(SolverDomain.RealNonnegative, "decisions_" + i);
model.AddDecision(decision);
model.AddConstraint("limits_of_" + i, downConstraint(i) <= decision <= upConstraint(i));
}
var fdecision = new Decision(SolverDomain.RealNonnegative, "formula");
//mymatrix is double[,]
model.AddConstraint("f_constraint_1", fdecision == matMult(transpose(model.Decisions.ToList()),
matMult(matrix(mymatrix), transpose(model.Decisions.ToList()))[0, 0]);
//myAalue is double = givvenValue^2
solverData.model.AddConstraint("f_constraint_2", fdecision == myAalue);
var udecision = new Decision(SolverDomain.RealNonnegative, "upto100");
model.AddConstraint("upto1_constraint_1", udecision == UpTo100Precent(model.Decisions.ToList()));
model.AddConstraint("upto1_constraint_2", udecision == 1);
solverData.model.AddGoal("goal", GoalKind.Maximize, CalcGoal(model.Decisions.ToList()));
model.AddDecision(udecision);
model.AddDecision(fdecision);
Solution solution = context.Solve(new HybridLocalSearchDirective() { TimeLimit = 60000 });
//add here I get solution.Quality == SolverQuality.Unknown
These are the functions I use in above code:
private Term[,] matrix(Double[,] m)
{
int rows = m.GetLength(0);
int cols = m.GetLength(1);
Term[,] r = new Term[rows, cols];
for (int row = 0; row < rows; row++)
for (int col = 0; col < cols; col++)
r[row, col] = m[row, col];
return r;
}
private Term[,] matMult(Term[,] a, Term[,] b)
{
int rows = a.GetLength(0);
int cols = b.GetLength(1);
Term[,] r = new Term[rows, cols];
for (int row = 0; row < rows; row++)
for (int col = 0; col < cols; col++)
{
r[row, col] = 0;
for (int k = 0; k < a.GetLength(1); k++)
{
r[row, col] += a[row, k] * b[k, col];
}
}
return r;
}
private Term[,] transpose(Term[,] m)
{
int rows = m.GetLength(0);
int cols = m.GetLength(1);
Term[,] r = new Term[cols, rows];
for (int row = 0; row < rows; row++)
for (int col = 0; col < cols; col++)
{
r[col, row] = m[row, col];
}
return r;
}
private Term UpTo100Precent(List<Decision> decisions)
{
Term to100 = 0;
foreach (var decision in decisions)
{
to100 += decision;
}
return to100;
}
private Term CalcGoal(List<Decision> decisions)
{
Term x = 0;
//A is double[]
for (i = 0; i < decisions.Count ; i++)
{
x += decisions[i] * A[1]
}
return x;
}
Does someone have a solution?

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