writing a new cell to a sheet apache poi - java

i am using following code, for reading a excel using apache poi, its a .xlsx file. Please let me know what i can do, to also alter a value of a cell, in each row as my loop keeps going. Thanks
import java.io.FileInputStream;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
String fileName = "C:/createCDN.xlsx";
FileInputStream fis = null;
fis = new FileInputStream(fileName);
XSSFWorkbook workbook = new XSSFWorkbook(fis);
FileOutputStream fos=new FileOutputStream(fileName);
XSSFSheet sheet = workbook.getSheetAt(0);
int totalRows=sheet.getLastRowNum();
for(int i=1;i<=totalRows;i++) {
XSSFRow row = sheet.getRow(i);
method.fillTextBox(row.getCell(0),"name", pageProp);
method.fillTextBox(row.getCell(0),"name", pageProp);
} //Do something here, or inside loop to write to lets say cell(2) of same row.
Thanks.

It should be like this:
for(int i = 1; i <= totalRows; i++) {
Row row = sheet.getRow(i);
Cell cell = row.getCell(2);
if (cell == null) {
cell = row.createCell(2);
}
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue("some value");
}
To save the workbook you could just write:
FileOutputStream fos = new FileOutputStream(fileName);
workbook.write(fos);
fos.close();
You should take a look at POI's Busy Developers' Guide.

at first you need to create the space in the excel file, like this:
for(int row = 0; row < 10 ; row++) {
sheet.createRow(row);
for(int column = 0; column < 10; column++) {
sheet.getRow(row).createCell(column);
}
}
then you can write the excel using this command:
sheet.getRow(row).getCell(column).setCellValue("hello");

Related

Converting excel (.xslx) file to java with cell that has hyperlink text won't be recognized and result is cell with empty value

This is the code which iterate through the excel file and extract the value from the cells:
public static <R> List<R> readAdvancedStudentSearchFromCSV(String fileName, CSVParser<R> parser) throws IOException {
List<R> rowsList = new ArrayList<>();
FileInputStream fis = new FileInputStream(fileName);
//Create Workbook instance for xlsx/xls file input stream
XSSFWorkbook workbook = null;
if(fileName.toLowerCase().endsWith("xlsx")){
workbook = new XSSFWorkbook(fis);
}
int numberOfSheets = workbook.getNumberOfSheets();
XSSFSheet sheet = workbook.getSheet("data");
int rowCount = sheet.getPhysicalNumberOfRows();
StringBuilder line = new StringBuilder();
for(int i=2; i<rowCount; i++){
String cellValue = "";
for(int j=0; j<10; j++){
try {
cellValue = sheet.getRow(i).getCell(j).getStringCellValue();
System.out.println(cellValue);
}catch(NullPointerException e){
cellValue = "";
}
if(cellValue.equals("")){
line.append(" ").append(" ").append(",");
}else {
line.append(" ").append(cellValue).append(",");
}
}
String[] attributes = line.toString().split(",");
R row = parser.toRow(attributes);
rowsList.add(row);
}
//close file input stream
fis.close();
return rowsList;
}
And this is how the excel file look like:
Problem:
When I reach cell No.7 (trying to get column named "Resume") with the value but I am getting empty string instead of getting the actual hypertextlink (as string or as link it is not important).
I have tried to use getHypertextLink method from Cell class but this did not help as well.
I have looked at: How to get hyperlink address from a cell in excel by using java?
which did not solve my issue.

How to speed up the formation of excel file?

I have such a code that generates using the POI library. The list contains 250,000 lines. The formation of an Excel file takes 30-40 minutes. Reading about POI, I realized that this is not normal. How to speed up the process?
private void create(List<User> list) throws IOException {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Statistic");
var rowCount = 0;
for (int i = 0; i < list.size(); i++) {
sheet.autoSizeColumn(i);
XSSFRow row = sheet.createRow(++rowCount);
XSSFCell loginCell = row.createCell(0);
loginCell.setCellValue(list.get(i).getLogin());
//...
XSSFCell amountSpecCell = row.createCell(9);
amountSpecCell.setCellValue(list.get(i).getLevel());
}
try {
FileOutputStream fileOutputStream = new FileOutputStream("myfilenew.xlsx");
workbook.write(fileOutputStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
workbook.close();
}
}

Writing to Excel with Java

I've searched around forums without prevail, so here I am.
I'm attempting to implement a method which writes to Excel, but every time it just corrupts the file. Here's a snippet of my code:
public static XSSFSheet printToExcel (ArrayList<String> al, Workbook wb, XSSFSheet s, FileWriter fw) throws FileNotFoundException, IOException {
int numOfRows = s.getPhysicalNumberOfRows();
for (int i = 0; i <= numOfRows; i++ ) {
XSSFRow row = s.createRow(i);
XSSFCell cell = row.createCell(i);
String text = al.get(i);
cell.setCellValue(text);
fw.write(text);
fw.close();
}
return s;
}
Hopefully you all can help me. I'm mostly self-taught so any advice will be appreciated.
This is an example which I wrote in another context but it will help you to start
import org.apache.poi.common.usermodel.HyperlinkType;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Hyperlink;
import org.apache.poi.xssf.usermodel.*;
import java.awt.*;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class WriteExcelBasic {
public static void main(String[] args) throws IOException {
String excelFileName = "/Users/home/Test3.xlsx";
FileOutputStream fos = new FileOutputStream(excelFileName);
XSSFWorkbook wb = new XSSFWorkbook();
XSSFCellStyle style = wb.createCellStyle();
XSSFSheet sheet = wb.createSheet("sheet");
XSSFFont urlFont = wb.createFont();// changed lines
urlFont.setFontHeight((short)(9*20));
// urlFont.setUnderline((byte)10);
//urlFont.setBold(true);
urlFont.setFontName("Arial");
urlFont.setItalic(true);
urlFont.setColor(new XSSFColor(Color.BLUE)); // changed lines
style.setFont(urlFont);
for (int r = 0; r < 3; r++) {
XSSFRow row = sheet.createRow(r);
for (int c = 0; c < 3; c++) {
XSSFCell cell = row.createCell(c);
Hyperlink link = wb.getCreationHelper().createHyperlink(HyperlinkType.URL);
String ss = "http://news.google.com/news/headlines?ned=us&hl=en";
//String ss = "swasdqde";
link.setAddress(ss);
cell.setHyperlink(link);
cell.setCellValue(ss);
if(r == 1) {
System.out.println("In yellow");
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setFillForegroundColor(new XSSFColor(Color.YELLOW));
} else {
System.out.println("In red");
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setFillForegroundColor(new XSSFColor(Color.RED));
}
cell.setCellStyle(style);
}
}
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
wb.write(baos);
byte[] myByteArray = baos.toByteArray();
fos.write(myByteArray);
fos.flush();
}
finally {
wb.close();
fos.close();
}
}
}

Issue with reading data with apache POI. Data is read but excel file is corrupted afterwards

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelData {
File fs;
FileInputStream fis;
XSSFWorkbook workbook;
XSSFSheet sheet;
FileOutputStream fos;
public ExcelData(String datafile_path) throws Exception{
fs=new File(datafile_path);
fis=new FileInputStream(fs);
workbook=new XSSFWorkbook(fis);
fos=new FileOutputStream(fs);
public Object readData(int sheet_num, int row_num, int column_num) throws Exception{
sheet=workbook.getSheetAt(sheet_num);
//sheet.getRow(row_num).getCell(column_num).CELL_TYPE_STRING;
Object data = null;
if (sheet.getRow(row_num).getCell(column_num).getCellType()==Cell.CELL_TYPE_STRING){
data=sheet.getRow(row_num).getCell(column_num).getStringCellValue();
} else if (sheet.getRow(row_num).getCell(column_num).getCellType()==Cell.CELL_TYPE_NUMERIC){
data=sheet.getRow(row_num).getCell(column_num).getNumericCellValue();
}
workbook.close();
//String data=sheet.getRow(row_num).getCell(column_num).getStringCellValue();
workbook.close();
fis.close();
return data;
}
----This code is working in reading the data. All the data is read successfully but after execution when look at the file, it is corrupted and size is 0 kb from 10 kb.
Following snippet works for ".xls" file extension
public String[][] readFile(String filePath) throws IOException, BiffException {
int totalNoOfRows, totalNoOfCols;
FileInputStream fis = new FileInputStream(filePath);
Workbook wb = Workbook.getWorkbook(fis);
// To get the access to the sheet
Sheet sh = wb.getSheet("Sheet1");
// To get the number of rows present in sheet
totalNoOfRows = sh.getRows();
// To get the number of columns present in sheet
totalNoOfCols = sh.getColumns();
String[][] excelData = new String[totalNoOfRows][totalNoOfCols];
for (int row = 0; row < totalNoOfRows; row++) {
for (int col = 0; col < totalNoOfCols; col++) {
excelData[row][col] = sh.getCell(col, row).getContents();
}
}
wb.close();
fis.close();
return excelData;
}

Reading cells from an Existing Excel File and Writing them into a new Excel File using Java

So I'm currently creating a program to read, edit and place data from an existing Excel file into a new Excel File using the JXL Java library. At this stage I will just like to read data from the existing Excel file and place it into the new one. Can't seem to find a good way of doing it and for future work what is the best way to edit the data (having certain columns) and placing them into the new Excel File.
Sorry if anything is unclear, just getting grips with Java and Stackoverflow.
import java.io.*;
import jxl.*;
import jxl.write.Number;
import jxl.write.*;
class Extraction {
private String inputFile;
String data;
public void setInputFile(String inputFile){
this.inputFile = inputFile;
}
public void read() throws IOException {
File spreadsheet = new File(inputFile);
Workbook w;
try {
w = Workbook.getWorkbook(spreadsheet);
Sheet page = w.getSheet(0);
File f = new File("C:\\Users\\alex\\Desktop\\New_Export.xls");
if (!f.exists()){
String FileName = "C:\\Users\\alex\\Desktop\\New_Export.xls";
WritableWorkbook excel = Workbook.createWorkbook(new File(FileName));
WritableSheet sheet = excel.createSheet("Sheet1", 0);
for (int y = 0; y < page.getRows(); y++){
for (int x = 0; x < page.getColumns(); x++){
Cell cell = page.getCell(x ,y +1);
CellType type = cell.getType();
if(type == CellType.LABEL || type == CellType.NUMBER){
data = cell.getContents();
System.out.println(data);
//To now input the read data into the new Excel File
sheet.addCell();
}
}
System.out.println(" ");
}
System.out.println("The File Has Successfully Been Created!");
excel.write();
excel.close();
}
else{
System.err.println("File is already created!");
}
}
catch(Exception e){
System.out.println(" ");
}
}
public static void main (String args[]) throws IOException{
Extraction reading = new Extraction();
reading.setInputFile("C:\\Users\\alex\\Desktop\\export.xls");
reading.read();
}
}
Using the "poi" from apache, you can use the below code to read the excel (*.xls)
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
private void readingExcel(String fileName) {
try (FileInputStream file = new FileInputStream(new File(fileName))) {
HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
for (Row row : sheet) {
Iterator<Cell> cellIterator = row.cellIterator();
for (Cell cell : row) {
System.out.println(cell.getStringCellValue());
}
}
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
For writing to excel
private File writingToExcel() {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sample-sheet");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("My Sample Value");
File file = new File(sheet.getSheetName());
return file;
}
However, if you want to use *.xlsx, the class used to read is
XSSFWorkbook workbook = new XSSFWorkbook (file);
XSSFSheet sheet = workbook.getSheetAt(0);

Categories