I am new to Selenium Web automation please be soft on me.
I have created a method to write an array content to an excel sheet.
I get no exception or error and I don't see data being written to excel sheet.
Name of excel sheet-mysheet.xlsx
Name of sheet within excel workbook:"FirstLevelMenu"
public class WriteExcelData {
XSSFWorkbook wb;
XSSFSheet sheet;
public void writeData(String path, String sheetName, String[] data) {
try {
File src = new File(path);
FileInputStream fis = new FileInputStream(src);
wb = new XSSFWorkbook(fis);
sheet = wb.getSheet(sheetName);
int rowCount = sheet.getLastRowNum() - sheet.getFirstRowNum();
Row row = sheet.getRow(0);
Row newRow = sheet.createRow(rowCount + 1);
for (int j = 0; j < row.getLastCellNum(); j++) {
Cell col = newRow.createCell(j);
col.setCellValue(data[j]);
}
fis.close();
FileOutputStream fout = new FileOutputStream(src);
wb.write(fout);
fout.close();
} catch (Exception e) {
e.getMessage();
}
}
public static void main(String[] args) {
WriteExcelData test=new WriteExcelData();
String[] data=new String[2];
data[0]="cat";
data[1]="cat";
test.writeData("C:\\mysheet.xlsx", "FirstLevelMenu", data);
}
}
As you are using a fresh xlsx sheet to write, please try below code...I am sure it will work :)
public static void main(String[] args) throws InvalidFormatException, IOException{
FileInputStream fis=new FileInputStream("D://Data.xlsx");
XSSFWorkbook wb= new XSSFWorkbook(fis);
//XSSFSheet sh= wb.getSheetAt(0); Or
XSSFSheet sh = wb.createSheet("Test");
XSSFRow row=sh.createRow(0);
XSSFCell cell= row.createCell(0);
//cell.setCellType(cell.CELL_TYPE_STRING);
cell.setCellValue("Ish Mishra");
FileOutputStream fos=new FileOutputStream("D:\\Data.xlsx");
wb.write(fos);
fos.close();
System.out.println("Excel File Written successfully");
Related
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();
}
}
I have written a code to add new row at 2nd position and then add values in the same
FileInputStream fis = new FileInputStream(theNewestFile);
#SuppressWarnings("resource")
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet spreadsheet = workbook.getSheetAt(0);
XSSFRow row;
try {
System.out.println(filename1);
InputStream myxls = new FileInputStream(filename1);
workbook = new XSSFWorkbook(myxls);
int rows=spreadsheet.getLastRowNum();
spreadsheet.shiftRows(2, rows, 1);
spreadsheet.createRow(1);
spreadsheet.getRow(1).createCell(0).setCellValue(column1Val);
FileOutputStream fileOut;
fileOut = new FileOutputStream(theNewestFile);
workbook.write(fileOut);
fileOut.close();
}
Iam trying to set the password using Hssf workbook and Biff8EncryptionKey.But iam not getting any response.
HSSFWorkbook writeWorkbook = new HSSFWorkbook();
Biff8EncryptionKey.setCurrentUserPassword("pass");
NPOIFSFileSystem fs = new NPOIFSFileSystem(new File("C:\\Users\\Visaws\\Desktop\\test4.xls"), true);
Please refer below code
private boolean importTables(InputStream stream, String fileName) throws Exception {
Workbook workbook;
if (fileName.toLowerCase().endsWith(".xls")) {
if (!TextUtils.isEmpty(decryptKey)) {
Biff8EncryptionKey.setCurrentUserPassword("1234567");
}
workbook = new HSSFWorkbook(stream);
} else {
throw new UnsupportedOperationException("Unsupported file format!");
}
stream.close();
int sheetNumber = workbook.getNumberOfSheets();
for (int i = 0; i < sheetNumber; i++) {
createTable(workbook.getSheetAt(i));
}
database.close();
return true;
}
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);
public class Excel {
public static void main(String[] args) throws IOException, FileNotFoundException {
try {
InputStream input = new BufferedInputStream(new FileInputStream("D:/one"));
POIFSFileSystem fs = new POIFSFileSystem(input);
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
Iterator rows = sheet.rowIterator();
while (rows.hasNext()) {
HSSFRow next = (HSSFRow) rows.next();
System.out.println("\n");
Iterator cells = next.cellIterator();
while (cells.hasNext()) {
HSSFCell next2 = (HSSFCell) cells.next();
if (HSSFCell.CELL_TYPE_NUMERIC == next2.getCellType()) {
System.out.println(next2.getNumericCellValue() + "");
} else if (HSSFCell.CELL_TYPE_STRING == next2.getCellType()) {
System.out.println(next2.getStringCellValue());
} else if (HSSFCell.CELL_TYPE_BOOLEAN == next2.getCellType()) {
System.out.println(next2.getBooleanCellValue() + "");
} else if (HSSFCell.CELL_TYPE_BLANK == next2.getCellType()) {
System.out.println("BLANK ");
} else {
System.out.println("unknown cell type");
}
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
you have not given the file extension in your code for your file "D:/one" is it an xls ot xlsx or csv .
This line:
InputStream input = new BufferedInputStream(new FileInputStream("D:/one"));
...should be something like:
InputStream input = new BufferedInputStream(new FileInputStream("D:/folder/filename.xls"));
...depending on your file location and extension of course.
As an aside, I highly recommend JExcelAPI and this tutorial by Lars Vogel.