I've created several Selenium tests in C# for testing a login page. Each test uses a different pair of credentials sourced from the same Excel spreadsheet, and each runs great by itself. I found a great bit of code on the web for being able to read the Excel spreadsheet and locating the data in a specific row for use. The problem that I'm running into is that the tests only run to completion in isolation and not when they are run in a series. In the latter case, only the first one succeeds whereas all the subsequent tests fail with a "text cannot be null" exception. I am suspicious that it could be something to do with Excel not getting disposed of properly between each test. Any ideas on how I can properly clean up the Excel stuff?
Here is the code where I instantiate the Excel object:
string path1 = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, #"SeleniumData\LoginBook.xlsx");
ExcelLib loginBook = new ExcelLib(path1);
Here is where I call the workbook:
rmMain_PageObject pageRMMain = new rmLogin_PageObject().Login(loginBook.ReadData(1, "UserName"), (loginBook.ReadData(1, "Password")));
Here is the method itself:
using Excel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutoTestProject1
{
public class ExcelLib
{
private DataTable ExcelToDataTable(string fileName)
{
//open file and returns as Stream
FileStream stream = File.Open(fileName, FileMode.Open, FileAccess.Read);
//Createopenxmlreader via ExcelReaderFactory
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream); //.xlsx
//Set the First Row as Column Name
excelReader.IsFirstRowAsColumnNames = true;
//Return as DataSet
DataSet result = excelReader.AsDataSet();
//Get all the Tables
DataTableCollection table = result.Tables;
//Store it in DataTable
DataTable resultTable = table["Sheet1"];
//return
return resultTable;
}
public ExcelLib(string fileName)
{
PopulateInCollection(fileName);
}
public class Datacollection
{
public int rowNumber { get; set; }
public int colNumber { get; set; } //test
public string colName { get; set; }
public string colValue { get; set; }
}
static List<Datacollection> dataCol = new List<Datacollection>();
private void PopulateInCollection(string fileName)
{
DataTable table = ExcelToDataTable(fileName);
//Iterate through the rows and columns of the Table
for (int row = 1; row <= table.Rows.Count; row++)
{
//for (int col = 0; col <= table.Columns.Count; col++)
for (int col = 0; col < table.Columns.Count; col++)
{
Datacollection dtTable = new Datacollection()
{
rowNumber = row,
colNumber = col, //test
colName = table.Columns[col].ColumnName,
colValue = table.Rows[row - 1][col].ToString()
};
//Add all the details for each row
dataCol.Add(dtTable);
}
}
}
var excelObject = new ExcelObject //what ever excel assy you are using
try{
}
catch(Exception e){
}
finally{
excelObject.Dispose();
}
Related
Excel Data reader read data from Excel sheet in order compare it with the UI dropdown values and see if they exists
I am trying to read data from excel sheet using below code
// methods to read data and parse the data into populate collection
using ExcelDataReader;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
namespace GorillaUITests.PageObjects
{
public class ExcelRead
{
public static List<Datacollection> dataCol = new List<Datacollection>();
public static DataTable ExcelToDataTable(string fileName)
{
using (var stream = File.Open(fileName, FileMode.Open, FileAccess.Read))
{
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
var result = reader.AsDataSet(new ExcelDataSetConfiguration()
{
UseColumnDataType = true,
ConfigureDataTable = (data) => new ExcelDataTableConfiguration()
{
UseHeaderRow = true
}
});
//Get all the Tables
DataTableCollection table = result.Tables;
//Store it in DataTable
DataTable resultTable = table["Sheet1"];
//return
return resultTable;
}
}
}
public static void PopulateInCollection(string fileName)
{
DataTable table = ExcelToDataTable(fileName);
//Iterate through the rows and columns of the Table
for (int row = 1; row <= table.Rows.Count; row++)
{
for (int col = 0; col < table.Columns.Count; col++)
{
Datacollection dtTable = new Datacollection()
{
rowNumber = row,
colName = table.Columns[col].ColumnName,
colValue = table.Rows[row - 1][col].ToString()
};
//Add all the details for each row
dataCol.Add(dtTable);
}
}
}
/// <summary>
/// Read data from Collection
/// </summary>
/// <param name="rowNumber"></param>
/// <param name="columnName"></param>
/// <returns></returns>
public static string ReadData(int rowNumber, string columnName)
{
try
{
//Retriving Data using LINQ to reduce much of iterations
string data = (from colData in dataCol
where colData.colName == columnName && colData.rowNumber == rowNumber
select colData.colValue).SingleOrDefault();
//var datas = dataCol.Where(x => x.colName == columnName && x.rowNumber == rowNumber).SingleOrDefault().colValue;
return data.ToString();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return null;
}
}
}
public class Datacollection
{
public int rowNumber { get; set; }
public string colName { get; set; }
public string colValue { get; set; }
}
}
// Test to see if we are able to read data
public void ReadDataFromExcel(string user, string pass)
{
// populate data in collection
try
{
ExcelRead.PopulateInCollection(#"C:\Users\username\Documents\GorillaUITests\GorillaUITests\Tests\Data\ReadDataTest.xlsx");
Debug.WriteLine("UserName:" + ExcelRead.ReadData(1, "UserName"));
Debug.WriteLine("Email:" + ExcelRead.ReadData(1, "Email"));
Debug.WriteLine("***********");
Debug.WriteLine("UserName:" + ExcelRead.ReadData(2, "UserName"));
Debug.WriteLine("Email:" + ExcelRead.ReadData(2, "Email"));
Debug.WriteLine("***********");
Debug.WriteLine("Username:" + ExcelRead.ReadData(2, "UserName"));
Debug.WriteLine("Email:" + ExcelRead.ReadData(2, "Email"));
Debug.WriteLine("***********");
catch (Exception e)
{
Console.WriteLine(e.Message);
}
And I see this error below
“Object reference not set to an instance of an object.”
Not sure what I am missing, Any inputs would be appreciated
I'm trying to write a parameterized NUnit test that executes twice. Each time it runs, it references a different row in a spreadsheet and gets the username and password based on int rowNum.
class Test
{
//Run the test twice
[Test,TestCase(1),TestCase(2)]
public void T101_LoginTestSuite_Valid(int rowNum)
{
Console.WriteLine(TestContext.CurrentContext.Test.MethodName); //Test Name
Console.WriteLine("Row number "+rowNum);// Value of rowNum
ExcelDataFactory.GetTestDataSet(TestContext.CurrentContext.Test.MethodName);
//Print out the credentials
Console.WriteLine(ExcelDataFactory.ReadData(rowNum,"username"));
Console.WriteLine(ExcelDataFactory.ReadData(rowNum, "password"));
}
}
Here is the excel
The first test case gets username and password correctly.
However the second test case returns blank (If I run this individually it will work!)
Below is the ExcelDataFactory code:
class ExcelDataFactory
{
//Get data from excel
private static DataTable ExcelToDataTable(String filename, String sheetName)
{
//Open file and returns as Stream
FileStream stream = File.Open(filename, FileMode.Open, FileAccess.Read);
//CreateOpenXmlReader via ExcelReaderFactory
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream); //.xlsx
//Return as DataSet and set the frist row as column name
DataSet result = excelReader.AsDataSet(new ExcelDataSetConfiguration()
{
ConfigureDataTable = (_) => new ExcelDataTableConfiguration()
{
UseHeaderRow = true
}
});
DataTableCollection table = result.Tables;
DataTable resultTable = table[sheetName];
//Close FileStream
stream.Close();
//Return
return resultTable;
}
//Put data into a collection
static List<DataCollection> dataCollection = new List<DataCollection>();
public static void PopulateInCollection(string fileName, String sheetName)
{
DataTable table = ExcelToDataTable(fileName,sheetName);
//Iterate through the rows and columns of the Table
for(int row = 1; row <= table.Rows.Count; row++)
{
for (int column = 0; column < table.Columns.Count; column++)
{
DataCollection dataTable = new DataCollection()
{
rowNumber = row,
columnName = table.Columns[column].ColumnName,
columnValue = table.Rows[row - 1][column].ToString()
};
//Add all the details for each row
dataCollection.Add(dataTable);
}
}
}
//Find the correct excel file and sheet
public static void GetTestDataSet(String testName)
{
String[] testNameSplit = testName.Split('_');
String filePath = MyProps.Default.TestData //Add path
+ testNameSplit[1]
+ "."
+ "xlsx";
PopulateInCollection(filePath, testNameSplit[0]);
}
public static string ReadData(int rowNumber, string columnName)
{
try
{
//Retriving Data using LINQ to reduce amount of iterations
string data = (from collectionData in dataCollection
where collectionData.columnName == columnName && collectionData.rowNumber == rowNumber
select collectionData.columnValue).SingleOrDefault();
//var data = dataCollection.Where(collectionData => collectionData.columnName == columnName && collectionData.rowNumber == rowNumber).SingleOrDefault().columnValue;
return data.ToString();
}
catch (Exception e)
{
e.StackTrace.ToString();
return null;
}
}
}
class DataCollection
{
public int rowNumber { get; set; }
public string columnName { get; set; }
public string columnValue { get; set; }
}
I suspect that the ExcelDataFactory.GetTestDataSet method is called in the wrong place, but I really am stumped as to why this is happening. Any ideas would be greatly appreciated.
I did some quick changes to ExcelDataFactory class, I removed the static references and now PopulateInCollection method returns a List that is declared and initialized at the start of the class.
using ExcelDataReader;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Wizuda_Selenium_Test_Automation
{
class ExcelDataFactory
{
List<DataCollection> dataCollection = new List<DataCollection>();
private static DataTable ExcelToDataTable(String filename, String sheetName)
{
//Open file and returns as Stream
FileStream stream = File.Open(filename, FileMode.Open, FileAccess.Read);
//CreateOpenXmlReader via ExcelReaderFactory
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream); //.xlsx
//Return as DataSet and set the frist row as column name
DataSet result = excelReader.AsDataSet(new ExcelDataSetConfiguration()
{
ConfigureDataTable = (_) => new ExcelDataTableConfiguration()
{
UseHeaderRow = true
}
});
DataTableCollection table = result.Tables;
DataTable resultTable = table[sheetName];
//Close FileStream
stream.Close();
//Return
return resultTable;
}
//static List<DataCollection> dataCollection = new List<DataCollection>();
public List<DataCollection> PopulateInCollection(string fileName, String sheetName)
{
dataCollection = new List<DataCollection>();
DataTable table = ExcelToDataTable(fileName,sheetName);
//Iterate through the rows and columns of the Table
for(int row = 1; row <= table.Rows.Count; row++)
{
for (int column = 0; column < table.Columns.Count; column++)
{
DataCollection dataTable = new DataCollection()
{
rowNumber = row,
columnName = table.Columns[column].ColumnName,
columnValue = table.Rows[row - 1][column].ToString()
};
//Add all the details for each row
dataCollection.Add(dataTable);
}
}
return dataCollection;
}
public string ReadData(int rowNumber, string columnName)
{
try
{
//Retriving Data using LINQ to reduce amount of iterations
string data = (from collectionData in dataCollection
where collectionData.columnName == columnName && collectionData.rowNumber == rowNumber
select collectionData.columnValue).SingleOrDefault();
//var data = dataCollection.Where(collectionData => collectionData.columnName == columnName && collectionData.rowNumber == rowNumber).SingleOrDefault().columnValue;
return data.ToString();
}
catch (Exception e)
{
e.StackTrace.ToString();
return null;
}
}
public void GetTestDataSet(String testName)
{
String[] testNameSplit = testName.Split('_');
String filePath = MyProps.Default.TestData //Add path
+ testNameSplit[1] //LoginTestSuite
+ "."
+ "xlsx"; //T101
PopulateInCollection(filePath, testNameSplit[0]);
}
}
class DataCollection
{
public int rowNumber { get; set; }
public string columnName { get; set; }
public string columnValue { get; set; }
}
}
I updated the test to create new instance of ExcelDataFactory
[Test,TestCase(1),TestCase(2)]
public void T101_LoginTestSuite_Valid(int rowNum)
{
ExcelDataFactory excelDataFactory = new ExcelDataFactory();
Console.WriteLine(TestContext.CurrentContext.Test.MethodName);
Console.WriteLine("Row number "+rowNum);
excelDataFactory.GetTestDataSet(TestContext.CurrentContext.Test.MethodName);
Console.WriteLine("username= "+ excelDataFactory.ReadData(rowNum,"username"));
Console.WriteLine("password= "+ excelDataFactory.ReadData(rowNum, "password"));
}
And now the test passes
I guess I need to go back and re-learn about the use static methods, thanks Kritner
I'm using NPOI to export data into excel.
So I created a List that will pull data from my database.
Now My question is how can I read my list data and write the data on my excel Sheet.
The following is my part of my code:
IWorkbook workbook;
workbook = new NPOI.XSSF.UserModel.XSSFWorkbook();
ISheet excelSheet = workbook.CreateSheet("Candidates");
IRow row = excelSheet.CreateRow(0);
foreach (var data in ApplicationList)
{
}
workbook.Write(fs);
So basically I need help on foreach (var data in ApplicationList)
While writing data cells can be created and SetCellValue can help set the data.
Below I have tried to iterate over a single column and list of strings.
This works fine on my system.
IWorkbook workbook = new HSSFWorkbook();
ISheet excelSheet = workbook.CreateSheet("Candidates");
IRow row = excelSheet.CreateRow(0);
var applicantList = new List<string> { "David", "Paul" };
var excelColumns = new[] { "Name" };
IRow headerRow = excelSheet.CreateRow(0);
var headerColumn = 0;
excelColumns.ToList().ForEach(excelColumn =>
{
var cell = headerRow.CreateCell(headerColumn);
cell.SetCellValue(excelColumn);
headerColumn++;
});
var rowCount = 1;
applicantList.ForEach(applicant => {
var row = excelSheet.CreateRow(rowCount);
var cellCount = 0;
excelColumns.ToList().ForEach(column => {
var cell = row.CreateCell(cellCount);
cell.SetCellValue(applicant);
cellCount++;
});
rowCount++;
});
var stream = new MemoryStream();
workbook.Write(stream);
string FilePath = "/Users/hemkumar/hem.xls"; //path to download
FileStream file = new FileStream(FilePath, FileMode.CreateNew,
FileAccess.Write);
stream.WriteTo(file);
file.Close();
stream.Close();
I hope it helps.
I know I am a little late here but I think it may help others
I have developed an excel utility with the use of the NPOI package, which can
Simply takes your data table or the collection
And Returns you excel while maintaining all the data table/list data type intact in the excel.
Github Code repo.: https://github.com/ansaridawood/.NET-Generic-Excel-Export-Sample/tree/master/GenericExcelExport/ExcelExport
Looking for a code explanation, you can find it here:
https://www.codeproject.com/Articles/1241654/Export-to-Excel-using-NPOI-Csharp-and-WEB-API
It uses NPOI DLL and it has 2 cs files to include and then you are good to go
Below is the first file for reference AbstractDataExport.cs:
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
namespace GenericExcelExport.ExcelExport
{
public interface IAbstractDataExport
{
HttpResponseMessage Export(List exportData, string fileName, string sheetName);
}
public abstract class AbstractDataExport : IAbstractDataExport
{
protected string _sheetName;
protected string _fileName;
protected List _headers;
protected List _type;
protected IWorkbook _workbook;
protected ISheet _sheet;
private const string DefaultSheetName = "Sheet1";
public HttpResponseMessage Export
(List exportData, string fileName, string sheetName = DefaultSheetName)
{
_fileName = fileName;
_sheetName = sheetName;
_workbook = new XSSFWorkbook(); //Creating New Excel object
_sheet = _workbook.CreateSheet(_sheetName); //Creating New Excel Sheet object
var headerStyle = _workbook.CreateCellStyle(); //Formatting
var headerFont = _workbook.CreateFont();
headerFont.IsBold = true;
headerStyle.SetFont(headerFont);
WriteData(exportData); //your list object to NPOI excel conversion happens here
//Header
var header = _sheet.CreateRow(0);
for (var i = 0; i < _headers.Count; i++)
{
var cell = header.CreateCell(i);
cell.SetCellValue(_headers[i]);
cell.CellStyle = headerStyle;
}
for (var i = 0; i < _headers.Count; i++)
{
_sheet.AutoSizeColumn(i);
}
using (var memoryStream = new MemoryStream()) //creating memoryStream
{
_workbook.Write(memoryStream);
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(memoryStream.ToArray())
};
response.Content.Headers.ContentType = new MediaTypeHeaderValue
("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.Content.Headers.ContentDisposition =
new ContentDispositionHeaderValue("attachment")
{
FileName = $"{_fileName}_{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx"
};
return response;
}
}
//Generic Definition to handle all types of List
public abstract void WriteData(List exportData);
}
}
and this the second and final file AbstractDataExportBridge.cs:
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Text.RegularExpressions;
namespace GenericExcelExport.ExcelExport
{
public class AbstractDataExportBridge : AbstractDataExport
{
public AbstractDataExportBridge()
{
_headers = new List<string>();
_type = new List<string>();
}
public override void WriteData<T>(List<T> exportData)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
foreach (PropertyDescriptor prop in properties)
{
var type = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
_type.Add(type.Name);
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ??
prop.PropertyType);
string name = Regex.Replace(prop.Name, "([A-Z])", " $1").Trim(); //space separated
//name by caps for header
_headers.Add(name);
}
foreach (T item in exportData)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
table.Rows.Add(row);
}
IRow sheetRow = null;
for (int i = 0; i < table.Rows.Count; i++)
{
sheetRow = _sheet.CreateRow(i + 1);
for (int j = 0; j < table.Columns.Count; j++)
{
ICell Row1 = sheetRow.CreateCell(j);
string type = _type[j].ToLower();
var currentCellValue = table.Rows[i][j];
if (currentCellValue != null &&
!string.IsNullOrEmpty(Convert.ToString(currentCellValue)))
{
if (type == "string")
{
Row1.SetCellValue(Convert.ToString(currentCellValue));
}
else if (type == "int32")
{
Row1.SetCellValue(Convert.ToInt32(currentCellValue));
}
else if (type == "double")
{
Row1.SetCellValue(Convert.ToDouble(currentCellValue));
}
}
else
{
Row1.SetCellValue(string.Empty);
}
}
}
}
}
}
For a detailed explanation, refer link provided in the beginning.
I'm using NPOI to export data into excel too.
But I have a list that will pull data from another excel file that created by NPOI.
Anyway, I think my solution to solve this problem, which is not much different from yours, can be effective.
After you see the code sample below, read the description.
await using var stream = new FileStream(#"C:\Users\Sina\Desktop\TestExcel.xlsx", FileMode.OpenOrCreate, FileAccess.Write);
IWorkbook workbook = new XSSFWorkbook();
var excelSheet = workbook.CreateSheet("TestSheet");
for (var i = 0; i < MyDataList.Count(); i++)
{
var row = excelSheet.CreateRow(i);
for (var j = 0; j < MyDataList[i].Cells.Count(); j++)
{
var cell = row.CreateCell(j);
cell.SetCellValue(MyDataList[i].Cells[j].ToString());
}
}
workbook.Write(stream);
As I said, instead of the list you got the data from your database, I've used a list that has data from another excel file that I pulled through NPOI.
You can see it in the code snippet above (MyDataList).
It is of type (List<IRow>).
You have to create as many rows as there are data in your list, so create it in a loop each time. var row = excelSheet.CreateRow(i)
Now notice that each row has several cells and I fill the cells with another loop and you need to create any number of cells in your row, so create it in this loop each time. var cell = row.CreateCell(j)
You can now use cell.SetCellValue() to set each cell data then use the data in your list instead of MyDataList[i].Cells[j] in that.
Note that the input type of the SetCellValue() method must be a string.
Now I want to add that I also used the AddRange() method instead of the second loop (like this - row.Cells.AddRange(FailedRowList[i].Cells)) but it didn't work, so if you can use that I would appreciate if you say it and let me know more. I hope my answer was helpful.
Thanks
I have used below code for generating excel but how can I pass this excel to blob
using (DataSet ds = finalDataSetOutput)
{
if (ds != null && ds.Tables.Count > 0)
{
using (ExcelPackage pck = new ExcelPackage())
{
foreach (DataTable dt in ds.Tables)
{
ExcelWorksheet ws = pck.Workbook.Worksheets.Add(dt.TableName);
ws.Cells["A1"].LoadFromDataTable(dt, true);
int i = 1;
foreach (DataColumn dc in dt.Columns)
{
i++;
if (dc.DataType == typeof(decimal))
ws.Column(i).Style.Numberformat.Format = "#0.00";
}
}
pck.SaveAs(new FileInfo(#"D:\SampleExcels\NewFile.xlsx"));
}
}
}
How to create excel and store in azure blob.
I recently did something similar, although I used an Azure Function to populate my Excel data from a collection rather than a DataSet. The principle should be the same - just make a connection to your Blob container and create a new CloudBlockBlob:
[FunctionName("WriteExcelToBlob")]
public async Task Run(
[TimerTrigger("*/30 * * * * *")] TimerInfo timer,
[Blob("excelFiles", FileAccess.Write, Connection = "Storage")] CloudBlobContainer blobContainer,
ILogger log
)
{
var fileNameSuffix = DateTime.Now.ToString("yyyyMMdd_HHmmss");
var myCollection = new List<MyObject>();
var newBlobName = $"myFile_{fileNameSuffix}.xlsx";
var newBlob = blobContainer.GetBlockBlobReference(newBlobName);
using (var excel = new ExcelPackage())
{
var worksheet = excel.Workbook.Worksheets.Add("My Worksheet");
worksheet.Cells.LoadFromCollection(myCollection);
using (var stream = await newBlob.OpenWriteAsync())
{
excel.SaveAs(stream);
}
}
}
Example class:
using System.ComponentModel;
public class MyObject
{
[Description("Name")]
public string Name { get; set; }
[Description("Home Address")]
public string HomeAddress { get; set; }
}
NOTE: Using the System.ComponentModel.Description decorator will allow you to have column headings in the output Excel. (Details here: EPPlus custom header column names)
I'm having some issues ASPxGridView on Getting data from Excel file. It's only showing the last data from Excel. I've tried to create custom unbound but got no luck. Tried to make it to the List<> and give it a try, no success. This is my code so far.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;
using DevExpress.Spreadsheet;
using DevExpress.Spreadsheet.Export;
using System.Data;
string FilePath
{
get { return Session["FilePath"] == null ? String.Empty : Session["FilePath"].ToString(); }
set { Session["FilePath"] = value; }
}
private DataTable GetTableFromExcel()
{
Workbook book = new Workbook();
book.InvalidFormatException += book_InvalidFormatException;
book.LoadDocument(FilePath);
Worksheet sheet = book.Worksheets.ActiveWorksheet;
Range range = sheet.GetUsedRange();
DataTable table = sheet.CreateDataTable(range, false);
DataTableExporter exporter = sheet.CreateDataTableExporter(range, table, false);
exporter.CellValueConversionError += exporter_CellValueConversionError;
exporter.Export();
return table;
}
void book_InvalidFormatException(object sender, SpreadsheetInvalidFormatExceptionEventArgs e)
{
}
void exporter_CellValueConversionError(object sender, CellValueConversionErrorEventArgs e)
{
e.Action = DataTableExporterAction.Continue;
e.DataTableValue = null;
}
protected void Upload_FileUploadComplete(object sender, DevExpress.Web.FileUploadCompleteEventArgs e)
{
FilePath = Page.MapPath("~/XlsTables/") + e.UploadedFile.FileName;
e.UploadedFile.SaveAs(FilePath);
}
public class invoice
{
public string nomor_invoice { get; set; }
}
protected void Grid_CustomCallback(object sender, DevExpress.Web.ASPxGridViewCustomCallbackEventArgs e)
{
if (!String.IsNullOrEmpty(FilePath))
{
DataTable table = GetTableFromExcel(); // Get The Excel
List<object> inv = new List<object>();
List<object> dekl = new List<object>();
List<invoice> invoiceList = new List<invoice>();
for (int i = 1; i < table.Rows.Count; i++)
{
DataRow row = table.Rows[i];
invoice nomorInvo = new invoice();
nomorInvo.nomor_invoice = row[1].ToString();
invoiceList.Add(nomorInvo);
string noDkl = row[0].ToString().ToUpper().Trim();
string[] nomor = noDkl.Split('-');
Decimal cab = decimal.Parse(nomor[0].ToString());
Decimal pmsrn = decimal.Parse(nomor[1].ToString());
Decimal reg = decimal.Parse(nomor[2].ToString());
string dkl = nomor[3].ToString();
Decimal cob = decimal.Parse(nomor[4].ToString());
Decimal bln = decimal.Parse(nomor[5].ToString());
Decimal thn = decimal.Parse(nomor[6].ToString());
string invo_no = row[1].ToString().Trim();
inv.Add(invo_no); // add to the list
inv.ToList();
SSREAS.DL.AE.Upload.dsImportir.APFDPE17Row invc = new DL.AE.Upload.dsImportirTableAdapters.APFDPE17TableAdapter().GetDataByDkinvc(cab, pmsrn, reg, dkl, cob, bln, thn, invo_no).SingleOrDefault();
// This is my select query. I used dataSet
if (invc != null)
{
for (int z = 0; z < inv.Count; z++)
{
odsGrid.SelectParameters["DKKDCB"].DefaultValue = cab.ToString();
odsGrid.SelectParameters["DKKDPS"].DefaultValue = pmsrn.ToString();
odsGrid.SelectParameters["DKRGDK"].DefaultValue = reg.ToString();
odsGrid.SelectParameters["DKDKL"].DefaultValue = dkl;
odsGrid.SelectParameters["DKCOB"].DefaultValue = cob.ToString();
odsGrid.SelectParameters["DKBLN"].DefaultValue = bln.ToString();
odsGrid.SelectParameters["DKTHN"].DefaultValue = thn.ToString();
odsGrid.SelectParameters["DKINVC"].DefaultValue = invo_no;
Grid.DataBind();
}
}
else if (invc == null)
{
return;
}
Grid.DataBind();
}
}
}
I've set breakpoint and 0 error occured, But when I upload the Excel File, It's show only 1 data instead of 2 and its the last row from excel. What is wrong with my code? A help would be appreciated. Thanks!
Persist the table in the cache or session in the page_prerender() event bind the data it will work.