I'm trying to upload an excel file with EPPlus. I'ts like my excel file was empty, but it has content inside.
Im getting this error:
worksheet.Dimension.Rows = 'worksheet.Dimension.Rows' threw an exception of type 'System.NullReferenceException'
on this line: int rowCount = worksheet.Dimension.Rows;
[HttpPost("Excel")]
public string UploadExcel(IFormFile file)
{
var filePath = Path.GetTempFileName();
FileInfo excel = new FileInfo(filePath);
using (ExcelPackage package = new ExcelPackage(excel))
{
StringBuilder sb = new StringBuilder();
ExcelWorksheet worksheet = package.Workbook.Worksheets[file.FileName];
int rowCount = worksheet.Dimension.Rows;
int ColCount = worksheet.Dimension.Columns;
bool bHeaderRow = true;
for (int row = 1; row <= rowCount; row++)
{
for (int col = 1; col <= ColCount; col++)
{
if (bHeaderRow)
{
sb.Append(worksheet.Cells[row, col].Value.ToString() + "\t");
}
else
{
sb.Append(worksheet.Cells[row, col].Value.ToString() + "\t");
}
}
sb.Append(Environment.NewLine);
}
return sb.ToString();
}
Can you verify that the workshseets are being loaded?
//examine in the debugger to make sure the worksheet you want is loaded
var worksheets = package.Workbook.Worksheets.ToList();
If that doesn't work, can you try one of these?
var worksheet = package.Workbook.Worksheets[0];
var worksheetFirst = package.Workbook.Worksheets.First();
UPDATE:
The real error is that you are trying to read a temp file with var filePath = Path.GetTempFileName();. You need to read an actual excel file. For example, you could use Path.GetFullPath("path/to/the/excel/file.xls");
Related
public async Task<List<IndiaCIT>> Import(IFormFile file)
{
var list = new List<IndiaCIT>();
using (var stream = new MemoryStream())
{
await file.CopyToAsync(stream);
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using (var package=new ExcelPackage(stream))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
var rowcount = worksheet.Dimension.Rows;
for (int row = 1; row <= rowcount; row++)
{
list.Add(new IndiaCIT {
NameCH = worksheet.Cells[row, 1].Value.ToString().Trim(),
City= worksheet.Cells[row, 2].Value.ToString().Trim(),
Age = worksheet.Cells[row, 3].Value.ToString().Trim(),
});
}
}
}
return list;
}
this is controller code and in model class declared the columns name and used it as IndiaCIT list in controller,. I want empty rows to get deleted
This could help:
For each row in the sheet, check if the cell in each column is empty. If so delete it.
var rowcount = worksheet.Dimension.Rows;
var maxColums = worksheet.Dimension.Columns;
for(int row = rowcount; row > 0; row--)
{
bool isRowEmpty = true;
for(int column = 1; column <= maxColumns; column++)
{
var cellEntry = worksheet.Cells[row, column].Value.ToString();
if(!string.IsNullOrEmpty(cellEntry)
{
isRowEmpty = false;
break;
}
}
if(!isRowEmpty)
continue;
else
worksheet.DeleteRow(row);
}
I generally use Spire.Xls to handle such problems. It works for me.
public IActionResult Test() {
//init workbook
Workbook workbook = new Workbook();
// load file
workbook.LoadFromFile("11.xlsx");
// get the first sheet
Worksheet sheet = workbook.Worksheets[0];
//delete blank row
for (int i = sheet.Rows.Count() - 1; i >= 0; i--)
{
if (sheet.Rows[i].IsBlank)
{
sheet.DeleteRow(i + 1);
}
}
//delete blank column
for (int j = sheet.Columns.Count() - 1; j >= 0; j--)
{
if (sheet.Columns[j].IsBlank)
{
sheet.DeleteColumn(j + 1);
}
}
//save as a new xls file
workbook.SaveToFile("new.xlsx", ExcelVersion.Version2016);
return Ok();
}
I use the EPPlus plugin to get information from Excel.The following code works perfectly, but how to control it when it gets an error after it reaches the empty Excel cell?
public async Task<IActionResult> AddExcellHorse(IFormFile ExcelFile)
{
using (var stream = new MemoryStream())
{
await ExcelFile.CopyToAsync(stream);
using (var package = new ExcelPackage(stream))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
var rowCount = worksheet.Dimension.Rows;
for (int i = 2; i <= rowCount; i++)
{
AddExcelHorse viewModel = new AddExcelHorse()
{
MicrochipCode = worksheet.Cells[i, 1].Value.ToString().Trim(),
EnHorseName = worksheet.Cells[i, 2].Value.ToString().Trim(),
EnFatherHorseName = worksheet.Cells[i, 3].Value.ToString().Trim(),
EnMotherHorseName = worksheet.Cells[i, 4].Value.ToString().Trim(),
};
if (viewModel.MicrochipCode != null)
{
if (!_admin.ChechMicrochip(viewModel.MicrochipCode))
{
_admin.AddExcelHorse(viewModel);
}
} }
return RedirectToAction(nameof(Index));
}
}
}
I assume you run into a null reference exception, because the cell value is null, then .ToString() cannot be called.
You could wrap everything in a seperate if-block:
if(worksheet.Cells[i, 1].Value != null)
{
MicrochipCode = worksheet.Cells[i, 1].Value.ToString().Trim(),
}
or you use the null propagation:
MicrochipCode = worksheet.Cells[i, 1].Value?.ToString().Trim(),
//or with default value, if null is not good enough.
MicrochipCode = worksheet.Cells[i, 1].Value?.ToString().Trim() ?? String.Empty,
I am a bit new to this but my goal is to import the data from a csv file into a sql table and include additional values for each row being the file name and date. I was able to accomplish this using entity frame work and iterating through each row of the file but with the size of the files it will take too long too actually complete.
I am looking for a method to accomplish this import faster. I was looking into potentially using csvhelper with sqlbulkcopy to accomplish this but was not sure if there was a way to pass in the additional values needed for each row.
public void Process(string filePath)
{
InputFilePath = filePath;
DateTime fileDate = DateTime.Today;
string[] fPath = Directory.GetFiles(InputFilePath);
foreach (var file in fPath)
{
string fileName = Path.GetFileName(file);
char[] delimiter = new char[] { '\t' };
try
{
using (var db = new DatabaseName())
{
using (var reader = new StreamReader(file))
{
string line;
int count = 0;
int sCount = 0;
reader.ReadLine();
reader.ReadLine();
while ((line = reader.ReadLine()) != null)
{
count++;
string[] row = line.Split(delimiter);
var rowload = new ImportDestinationTable()
{
ImportCol0 = row[0],
ImportCol1 = row[1],
ImportCol2 = TryParseNullable(row[2]),
ImportCol3 = row[3],
ImportCol4 = row[4],
ImportCol5 = row[5],
IMPORT_FILE_NM = fileName,
IMPORT_DT = fileDate
};
db.ImportDestinationTable.Add(rowload);
if (count > 100)
{
db.SaveChanges();
count = 0;
}
}
db.SaveChanges();
//ReadLine();
}
}
}
static int? TryParseNullable(string val)
{
int outValue;
return int.TryParse(val, out outValue) ? (int?)outValue : null;
}
}
I'm currently new to TestNG using java. I'm trying to read the values from an excel using poi apache 4.0
public static void read2dRowExcelFile2(String filePath) throws IOException {
try {
FileInputStream fis = new FileInputStream(new File(filePath));
HSSFWorkbook wb = new HSSFWorkbook(fis);
HSSFSheet sheet = wb.getSheet("PerLocation");
Object[][] tableArr = new String[sheet.getLastRowNum() + 1][];
int arrNo1 = 0;
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
Row row = sheet.getRow(i);
int arrNo2 = 0;
for (int j = 0; j < row.getLastCellNum(); j++) {
String cellValue = row.getCell(j).getStringCellValue();
System.out.println(acellValue);
//tableArr[arrNo1][arrNo2] = cellValue;
System.out.println("test");
arrNo2++;
}
arrNo1++;
}
wb.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Code above displays the values on the console. My goal is to store those values to an Object. Something like [{London, Blue},{Tokyo,Yellow},{Manila,Red}] so I can pass them to a dataProvider
If I run the code above, it displays :
London
BLue
Tokyo
Yellow
Manila
Red
But If i uncomment this line :
//tableArr[arrNo1][arrNo2] = cellValue;
The output is only :
London
03-08-19 : After I enabled stacktrace, it says : java.lang.NullPointerException
which pertains to this code :
tableArr[arrNo1][arrNo2] = cellValue;
From your code,
Object[][] tableArr = new String[sheet.getLastRowNum() + 1][];
At the time of initialization of array, your are setting size of first dimension but not the second . You need to initialize array for second dimension before you access it.
Refer below example:
public static void main(String[] args) {
//read rows size
int numOfRows = 3;
String[][] tableArr = new String[numOfRows][];
for (int row = 0; row <3; row++) {
//read columns size
int numOfColsInRow = 3;
tableArr[row]=new String[numOfColsInRow];
for (int col = 0; col < 3; col++) {
String cellValue = "cell-" + row+""+col;//read cell value
tableArr[row][col] = cellValue;
}
}
for(String[] row: tableArr) {
System.out.println(Arrays.toString(row));
}
}
Running above code with generate expected output:
[cell-00, cell-01, cell-02]
[cell-10, cell-11, cell-12]
[cell-20, cell-21, cell-22]
To reproduce your problem you can try commenting line which initialize array for second dimension in the code and you will see Exception in thread "main" java.lang.NullPointerException
.
//tableArr[row]=new String[numOfColsInRow];
To avoid all such issues you also can check if any exiting TestNG data-provider extension satisfies your need.
This is my Util function :
// Method to write into an XL
public static void writeXL(String fPath, String fSheet, String[][] xData) throws Exception{
File outFile = new File(fPath);
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet osheet = wb.createSheet(fSheet);
int xR_TS = xData.length;
// System.out.println(xR_TS);
int xC_TS = xData[0].length;
// System.out.println(xC_TS);
for (int myrow = 0; myrow < xR_TS; myrow++) {
HSSFRow row = osheet.createRow(myrow);
for (int mycol = 0; mycol < xC_TS; mycol++) {
HSSFCell cell = row.createCell(mycol);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setCellValue(xData[myrow][mycol]);
}
FileOutputStream fOut = new FileOutputStream(outFile);
wb.write(fOut);
fOut.flush();
fOut.close();
}
}
While I am trying to write into this excel using the below command :
// i is the loop value
xlActualTot[i][5]=PayAmt; // where PayAmt is the value I am capturing from website and storing it in xlActualTot[0][5] (type is String[][])
Utils.writeXL("<filepath>","TestData",xlActualTot);
I am getting the below exception at "xlActualTot[0][5]=PayAmt" this line :
java.lang.NullPointerException
Can you all please suggest why I am getting that error?