I have one listbox in XAML and i am binging some data with this litbox.like bellow
lstsumitedreport = new ObservableCollection<ClsGetSubmittedReport>();
if (ResultCode == "1")
{
JArray arry = (JArray)obj["GetSubmittedReportComment"];
if (arry != null)
{
total = arry.Count;
for (int i = 0; i < arry.Count; i++)
{
JObject obj1 = (JObject)arry[i];
int reportId = (int)obj1["ReportId"];
string positiveCmnt = (string)obj1["PositiveComment"];
string NagativeCmnt = (string)obj1["negativecomment"];
DateTime dt = (DateTime)obj1["TimeStamp"];
string time = (string)obj1["TimeStampString"];
DateTime dtlocal = DateTime.ParseExact(time, "yyyy/MM/dd HH:mm:ss", CultureInfo.InvariantCulture);
string timestamp = dtlocal.ToString("MM/dd/yyyy hh:mm tt", CultureInfo.InvariantCulture);
lstsumitedreport.Add(new ClsGetSubmittedReport(reportId, positiveCmnt, NagativeCmnt, timestamp, Csi, goodimagepath, bedimagepath, goodimgline, bedimgline, font, PHeight, NHeight));
}
}
TransactionList.ItemsSource = null;
this.TransactionList.ItemsSource = lstsumitedreport;
tbOutstandingCount.Text = total.ToString();
}
Here transection list is my listbox name.
after debuging of bellow line it will take to much time to display data.
this.TransactionList.ItemsSource = lstsumitedreport;
how can i solve this proble
Related
I am porting Excel Interop PivotTable code to EPPlus. I'm at a sticking point in generating a calculated field value. In Excel Interop I can do it this way:
pvt.AddDataField(pvt.PivotFields("TotalQty"), "Total Packages", XlConsolidationFunction.xlSum).NumberFormat = "###,##0";
pvt.AddDataField(pvt.PivotFields("TotalPrice"), "Total Purchases", XlConsolidationFunction.xlSum).NumberFormat = "$#,##0.00";
PivotField avg = pvt.CalculatedFields().Add("Average Price", "=TotalPrice/TotalQty", true);
avg.Orientation = XlPivotFieldOrientation.xlDataField;
avg.NumberFormat = "$###0.00";
With this the "Average Price" value on the PivotTable displays the value for TotalPrice divided by TotalQty.
But how to do it in EPPlus? I can create the "plain vanilla" data fields like so:
var totQtyField = pivotTable.Fields["TotalQty"];
pivotTable.DataFields.Add(totQtyField);
var totPriceField = pivotTable.Fields["TotalPrice"];
pivotTable.DataFields.Add(totPriceField);
...but when it comes to calculating a value, I'm baffled. My starting point was an online example for sums like so:
pivotTable.DataFields.Add(pivotTable.Fields["AvgPrice"]).Function =
OfficeOpenXml.Table.PivotTable.DataFieldFunctions.Sum();
So I tried the following, but none of them is right:
pivotTable.DataFields.Add(pivotTable.Fields["AvgPrice"]).Function =
OfficeOpenXml.Table.PivotTable.DataFieldFunctions.Average(totPriceField, totQtyField);
pivotTable.DataFields.Add(pivotTable.Fields["AvgPrice"]).Function = "TotalPrice/TotalQty";
pivotTable.DataFields.Add(pivotTable.Fields["AvgPrice"]) = "TotalPrice/TotalQty";
pivotTable.DataFields.Add(pivotTable.Fields["AvgPrice"]) = totPriceField / totQtyField;
pivotTable.DataFields.Add(pivotTable.Fields["AvgPrice"]).Function =
OfficeOpenXml.Table.PivotTable.
DataFieldFunctions.Product(totPriceField/totQtyField);
None of those flailings even compile. What adjustment do I need to make, or what completely new approach do I need to take?
UPDATE
I could calculate the values and put them on the data sheet and reference it that way; but is this really the only/best way to do this?
UPDATE 2
I did that (added the vals directly to the sheet that contains the source data for the Pivot Table):
var avgCell = rawDataWorksheet.Cells[_lastRowAddedRawData + 1, 9];
if ((TotalPrice < 0.0M) || (Quantity < 1))
{
avgCell.Value = 0.0;
}
else
{
avgCell.Value = TotalPrice / Quantity;
}
var prcntgCell = rawDataWorksheet.Cells[_lastRowAddedRawData + 1, 10];
if ((TotalPrice < 0.0M) || (MonthYear == String.Empty))
{
prcntgCell.Value = 0.0;
}
else
{
prcntgCell.Value = GetPercentageOfItemForMonthYear(TotalPrice, MonthYear);
}
private double GetPercentageOfItemForMonthYear(decimal totPrice, strin
monthYear)
{
decimal totalForMonthYear = monthlySales[monthYear];
double prcntg = GetPercentageOfItem(totPrice, totalForMonthYear);
return prcntg;
}
private double GetPercentageOfItem(decimal portionOfTotal, decimal
grandTotal)
{
if ((portionOfTotal <= 0.0M) || (grandTotal <= 0.0M))
{
return 0.0;
}
if (portionOfTotal == grandTotal)
{
return 100.0;
}
double d = Convert.ToDouble(portionOfTotal)
/ Convert.ToDouble(grandTotal) * 100;
return Math.Round(d, 2);
}
...but still would like to know how that's accomplishable using calculated fields while the PivotTable is being created.
EPPlus does not currently support calculated fields in PivotTables. I used the following workaround:
using System.Linq;
using System.Xml;
using OfficeOpenXml.Table.PivotTable;
using ReflectionMagic;
public static ExcelPivotTableField AddCalculatedField(this ExcelPivotTable pivotTable, string calcFieldName, string formula)
{
var dynamicPivotTable = pivotTable.AsDynamic();
var maxIndex = pivotTable.Fields.Max(f => f.Index);
const string schemaMain = #"http://schemas.openxmlformats.org/spreadsheetml/2006/main";
var cacheTopNode = dynamicPivotTable.CacheDefinition.CacheDefinitionXml.SelectSingleNode("//d:cacheFields", dynamicPivotTable.NameSpaceManager);
cacheTopNode.SetAttribute("count", (int.Parse(cacheTopNode.GetAttribute("count")) + 1).ToString());
var cacheFieldNode = dynamicPivotTable.CacheDefinition.CacheDefinitionXml.CreateElement("cacheField", schemaMain);
cacheFieldNode.SetAttribute("name", calcFieldName);
cacheFieldNode.SetAttribute("databaseField", "0");
cacheFieldNode.SetAttribute("formula", formula);
cacheFieldNode.SetAttribute("numFmtId", "0");
cacheTopNode.AppendChild(cacheFieldNode);
var topNode = dynamicPivotTable.PivotTableXml.SelectSingleNode("//d:pivotFields", dynamicPivotTable.NameSpaceManager);
topNode.SetAttribute("count", (int.Parse(topNode.GetAttribute("count")) + 1).ToString());
XmlElement fieldNode = dynamicPivotTable.PivotTableXml.CreateElement("pivotField", schemaMain);
fieldNode.SetAttribute("compact", "0");
fieldNode.SetAttribute("outline", "0");
fieldNode.SetAttribute("showAll", "0");
fieldNode.SetAttribute("defaultSubtotal", "0");
topNode.AppendChild(fieldNode);
var excelPivotTableFieldType = typeof(ExcelPivotTableField).AsDynamicType();
var excelPivotTableField = excelPivotTableFieldType.New((XmlNamespaceManager)dynamicPivotTable.NameSpaceManager, fieldNode, (ExcelPivotTable)dynamicPivotTable, maxIndex + 1, maxIndex + 1);
excelPivotTableField.SetCacheFieldNode(cacheFieldNode);
dynamicPivotTable.Fields.AddInternal(excelPivotTableField);
return pivotTable.Fields.First(f => f.Name == calcFieldName);
}
Example usage:
var calc1 = pivotTable.AddCalculatedField("Calc1", "BCol*BCol");
var dataField = pivotTable.DataFields.Add(calc1);
dataField.Function = DataFieldFunctions.Sum;
dataField.Name = "Override Name";
I've tried implementing thishttps://www.paragon-inc.com/resources/blogs-posts/easy_excel_interaction_pt6 on an ASP.NET MVC 5 Application.
//SEE CODE BELOW
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
var regPIN = DB.AspNetUsers.Where(i => i.Id == user.Id).Select(i => i.registrationPIN).FirstOrDefault();
if (file != null && file.ContentLength > 0)
{
var extension = Path.GetExtension(file.FileName);
var excelFile = Path.Combine(Server.MapPath("~/App_Data/BulkImports"),regPIN + extension);
if (System.IO.File.Exists(excelFile))
{
System.IO.File.Delete(excelFile);
}
else if (file.ContentType == "application/vnd.ms-excel" || file.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
{
file.SaveAs(excelFile);//WORKS FINE
//BEGINING OF IMPORT
FileInfo eFile = new FileInfo(excelFile);
using (var excelPackage = new ExcelPackage(eFile))
{
if (!eFile.Name.EndsWith("xlsx"))//Return ModelState.AddModelError()
{ ModelState.AddModelError("", "Incompartible Excel Document. Please use MSExcel 2007 and Above!"); }
else
{
var worksheet = excelPackage.Workbook.Worksheets[1];
if (worksheet == null) { ModelState.AddModelError("", "Wrong Excel Format!"); }// return ImportResults.WrongFormat;
else
{
var lastRow = worksheet.Dimension.End.Row;
while (lastRow >= 1)
{
var range = worksheet.Cells[lastRow, 1, lastRow, 3];
if (range.Any(c => c.Value != null))
{ break; }
lastRow--;
}
using (var db = new BlackBox_FinaleEntities())// var db = new BlackBox_FinaleEntities())
{
for (var row = 2; row <= lastRow; row++)
{
var newPerson = new personalDetails
{
identificationType = worksheet.Cells[row, 1].Value.ToString(),
idNumber = worksheet.Cells[row, 2].Value.ToString(),
idSerial = worksheet.Cells[row, 3].Value.ToString(),
fullName = worksheet.Cells[row, 4].Value.ToString(),
dob = DateTime.Parse(worksheet.Cells[row, 5].Value.ToString()),
gender = worksheet.Cells[row, 6].Value.ToString()
};
DB.personalDetails.Add(newPerson);
try { db.SaveChanges(); }
catch (Exception) { }
}
}
}
}
}//END OF IMPORT
ViewBag.Message = "Your file was successfully uploaded.";
return RedirectToAction("Index");
}
ViewBag.Message = "Error: Your file was not uploaded. Ensure you upload an excel workbook file.";
return View();
}
else
{
ViewBag.Message = "Error: Your file was not uploaded. Ensure you upload an excel workbook file.";
return View();
}
}
See Picture Error
Any help would be greatly appreciated mates.
you can do like this:
public bool readXLS(string FilePath)
{
FileInfo existingFile = new FileInfo(FilePath);
using (ExcelPackage package = new ExcelPackage(existingFile))
{
//get the first worksheet in the workbook
ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
int colCount = worksheet.Dimension.End.Column; //get Column Count
int rowCount = worksheet.Dimension.End.Row; //get row count
string queryString = "INSERT INTO tableName VALUES"; //Here I am using "blind insert". You can specify the column names Blient inset is strongly not recommanded
string eachVal = "";
bool status;
for (int row = 1; row <= rowCount; row++)
{
queryString += "(";
for (int col = 1; col <= colCount; col++)
{
eachVal = worksheet.Cells[row, col].Value.ToString().Trim();
queryString += "'" + eachVal + "',";
}
queryString = queryString.Remove(queryString.Length - 1, 1); //removing last comma (,) from the string
if (row % 1000 == 0) //On every 1000 query will execute, as maximum of 1000 will be executed at a time.
{
queryString += ")";
status = this.runQuery(queryString); //executing query
if (status == false)
return status;
queryString = "INSERT INTO tableName VALUES";
}
else
{
queryString += "),";
}
}
queryString = queryString.Remove(queryString.Length - 1, 1); //removing last comma (,) from the string
status = this.runQuery(queryString); //executing query
return status;
}
}
Details: http://sforsuresh.in/read-data-excel-sheet-insert-database-table-c/
I have below code in Groovy. Basically what I'm trying is to read the set of Input records and merge them into 1 or more records with common key combination.
The Key combination is as shown below. After reading the input file, I have written the key and fields into HashMap ( see code). But now I need to check the key in the input file , if the key is seen then I have write the output record otherwise I just need to write a output record as without merging. My questions
what is the command to insert a field in Output record ?.
import java.util.Properties;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
for( int i = 0; i < dataContext.getDataCount(); i++ ) {
InputStream is = dataContext.getStream(i);
Properties props = dataContext.getProperties(i);
reader = new BufferedReader(new InputStreamReader(is));
/* This is how to declare HashMap */
def forcastMap = [:]
String Key;
String Shipfrom = "";
String Item = "";
String Fcast = "";
String Shipto = "";
String Planned_Arrival_Date = "";
String Qty = "";
String PrevKey = "";
List<String> line = null
while ((line = reader.readLine()) != null)
{
if(line.length() > 20) //Make sure it is a data line so we can do substring manipulation
{
Shipfrom = line.substring(35,12)
Item = line.substring(50,50)
Fcast = line.substring(10,50)
Shipto = line.substring(75,10)
Planned_Arrival_Date = line.substring(85,8)
Qty = line.substring(90,12)
Key = (Shipfrom + Item + Fcast + Shipto)
forcastMap.put(Key,Planned_Arrival_Date,Qty)
if key != PrevKey {
}
}
}
//dataContext.storeStream(is, props);
}
im struggeling for below scenario.
Application displayed records of 100 suppliers in one table have three columns namely as ID,Company name and Subscription name.
i want to take input from my excel sheet say company name"xyz" and using that input i have to click on subscription name details link so application will navigates me next page.
Sample code i have created as below:
`public static void main(String[] args) throws BiffException, IOException, Exception {
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
//Workbook location
Workbook wBook = Workbook.getWorkbook(new File("C:\Users\amit.bhagwat\Documents\TestData\SampleData.xls"));
//get sheet
jxl.Sheet Sheet = wBook.getSheet(0);
//loop
for(int i=1; i<Sheet.getRows(); i++)
{
driver.get("http://206.132.42.243/Web");
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
driver.findElement(By.xpath("//input[#id='UserName']")).sendKeys(Sheet.getCell(0, i).getContents());
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
driver.findElement(By.xpath("//input[#id='Password']")).sendKeys(Sheet.getCell(1, i).getContents());
driver.findElement(By.xpath("//input[#id='Password']")).sendKeys(Sheet.getCell(1, i).getContents());
Thread.sleep(40);
driver.findElement(By.xpath("//input[#name='Login']")).click();
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
driver.findElement(By.xpath("//a[contains(text(),'Task')]")).click();
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
driver.findElement(By.xpath("//a[contains(text(),'Data Checking')]")).click();
jxl.Sheet Sheet2 = wBook.getSheet(0);
WebElement kancheck = driver.findElement(By.name("Grant & Brown"));
kancheck.click();
System.out.println(kancheck.isSelected());
driver.findElement(By.xpath("//a[contains(text(),'Data Checking')]")).sendKeys(Sheet2.getCell(1, i).getContents());
Thread.sleep(40);` enter code here
As far as I could understand, you are trying to read the file from a remote location and then read the information from it. It would be a good practice if you can use Apache POI library to read contents at run-time.
In my project, I read all the contents from an excel sheet usingApache POI library to set the values of my variables. Here is a code snippet on how i achieved it. Hopefully this will guide you to a proper solution. :)
public void readExcelDoc() throws FileNotFoundException, IOException
{
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream("excelDoc//scripts.xls"));
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row = null;
HSSFCell cell = null;
int rows = 0; // No of rows
// rows = sheet.getPhysicalNumberOfRows();
rows = sheet.getLastRowNum();
int cols = 2; // No of columns
int tmp = 0;
// This trick ensures that we get the data properly even if it doesn't start from first few rows
for(int i = 0; i < 10 || i < rows; i++) {
row = sheet.getRow(i);
if(row != null) {
tmp = sheet.getRow(i).getPhysicalNumberOfCells();
if(tmp > cols) cols = tmp;
}
}
int testRowNo = 0;
String rowName = "Test Name";
String columnValue = " ";
//Iterate through Row and columns here. Excluding 1st row for title names
for(int r = 1; r <= rows; r++) {
row = sheet.getRow(r);
if(row != null) {
//Browse through columns using c
for(int c = 0; c < cols; c++) {
if(c==0) //Only taking data from Cell 0; Ignoring any other inputs
{
cell = row.getCell((short)c);
try
{
if(cell.getStringCellValue().contains(rowName))
{
testRowNo =row.getRowNum();
}
if(testRowNo > 0 )
{
if(cell.getColumnIndex() == 0 && row.getRowNum() > testRowNo && cell.getStringCellValue().length() !=0)
{
try{
String cellValue = cell.getStringCellValue().toLowerCase();
//System.out.println(cellValue);
scriptType.add(cellValue);
}
catch(IllegalStateException e)
{
e.printStackTrace();
scriptType.add(cell.getStringCellValue());
}
}
}
}
catch(NullPointerException e)
{
}
}
if(c==1)
{
cell = row.getCell((short)c); //this sets the column number
if(testRowNo == 0)
{
try{
String cellValue = cell.getStringCellValue();
//System.out.println(cellValue);
columnValue = cellValue;
}
catch(IllegalStateException e)
{
String cellValue = cell.toString();
columnValue = cellValue;
}
catch(NullPointerException e)
{
String cellValue = nodata;
columnValue = cellValue;
}
}
}
if(c==2)
{
cell = row.getCell((short)c); //this sets the column number
if(testRowNo == 0)
{
try{
String cellValue = cell.getStringCellValue();
//System.out.println(cellValue);
inputParameters.put(cellValue, columnValue);
}
catch(IllegalStateException e)
{
String cellValue = cell.toString();
inputParameters.put(cellValue, columnValue);
}
catch(NullPointerException e)
{
String cellValue = nodata;
inputParameters.put(cellValue, columnValue);
}
}
}
}
}
}
System.out.println("---------The parameters set from excel are : ---------");
#SuppressWarnings("rawtypes")
Iterator iterator = inputParameters.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next().toString();
String value = inputParameters.get(key).toString();
System.out.println(key + " : " + value);
}
}
public partial class logRead : Form
{
DataSet ds = new DataSet();
DataTable tab = new DataTable();
public logRead()
{
InitializeComponent();
}
string line;
private void BtnUser_Click(object sender, EventArgs e)
{
DataRow[] filteredRows = tab.Select("Username = '"+cmbUsername.Text+"'");
DataTable dt = filteredRows.CopyToDataTable();
dgv1.DataSource = dt;
txtcount.Text = dgv1.Rows.Count.ToString();
}
private void btnsearch_Click(object sender, EventArgs e)
{
dtmDate.CustomFormat = "dd MMM yyyy hh mm ss";
DataRow[] filteredRows = tab.Select("Datetime = '" +dtmDate.Text + "'");
DataTable dt = filteredRows.CopyToDataTable();
dgv1.DataSource = dt;
}
private void logRead_Load(object sender, EventArgs e)
{
StreamReader strRead = new StreamReader("D:\\login.hml");
string line;
line = strRead.ReadToEnd();
DataRow row = null;
tab.Columns.Add("Ipaddress");
tab.Columns.Add("Sysname");
tab.Columns.Add("Username");
tab.Columns.Add("Text");
tab.Columns.Add("Datetime");
string[] rows = line.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string r in rows)
{
string[] columns = r.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
if (columns.Length <= tab.Columns.Count)
{
row = tab.NewRow();
for (int i = 0; i < columns.Length; i++)
row[i] = columns[i];
tab.Rows.Add(row);
}
}
ds.Tables.Add(tab);
dgv1.DataSource = ds.Tables[0];
txtcount.Text = dgv1.Rows.Count.ToString();
}
}}
i have alogfile ,when form load itself i write code to fill datagridview ,i use temporarly datatable and dataset and filling in to datagridview ,and i use combobox to fill all user names temporarly and if i click any name on combobox what are all names that information fill in datagridview i write that code in btn userclik now i want log table by month wise or date i taken two comboboxess and one combox fill datetime picker and one more months i fill ,now i want to click and month i want to show month wise dat in datagridview ,i write that code search click i am not getting.(dis is in windows forms)one more thng i am not using database also,plz check the code.
var formatPattern = "dd MMM yyyy hh mm ss";
DateTime parsedDate;
var culture = System.Globalization.CultureInfo.InvariantCulture; // use CurentCulture if you want to use the current culture instead which might change
bool success = DateTime.TryParseExact(dtmDate.Text, formatPattern, culture, DateTimeStyles.None, out parsedDate);
if (success)
Instead of using a for DataTable.Select i would use the DateTime in a Linq-To-DataSet query. You can use DateTime.TryParseExact to parse the string to DateTime.
var formatPattern = "dd MMM yyyy hh mm ss";
DateTime parsedDate;
var culture = System.Globalization.CultureInfo.InvariantCulture; // use CurentCulture if you want to use the current culture instead which might change
bool success = DateTime.TryParseExact(dtmDate.Text, formatPattern, culture, DateTimeStyles.None, out parsedDate);
if (success)
{
// assuming you want all rows of the same day not the same second:
var filteredRows = tab.AsEnumerable()
.Where(r => r.Field<DateTime>("Datetime").Date == parsedDate.Date);
dgv1.DataSource = filteredRows.CopyToDataTable();
}