how to set the password to excel sheet using java - java

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;
}

Related

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();
}
}

Unable to write to an excel (Selenium WebDriver) - Apache POI

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");

The constructor XSSFWorkbook(FileInputStream) is undefined

Iam trying to read data from an excel file, i am using the following code :
File Excel = new File("C:\\Users\\data.xlsx");
FileInputStream fis = new FileInputStream(Excel);
XSSFWorkbook wb = new XSSFWorkbook(fis);
but i am getting the compilation error as
The constructor XSSFWorkbook(FileInputStream) is undefined
try this one
Its work for me
Successfully.........
try (FileInputStream file = new FileInputStream(new File(filename))) {
**Workbook workbook = WorkbookFactory.create(file);**
try{
String filename="C:\\Users\\NIKITA\\Documents\\NetBeansProjects\\NickPrac\\exceldatabase.xlsx";
out.print(filename);
try (FileInputStream file = new FileInputStream(new File(filename))) {
Workbook workbook = WorkbookFactory.create(file);
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test" , "root" , "root");
String jdbc_insert_sql = "INSERT INTO employee"+"VALUES(?,?,?)";
PreparedStatement preStatement = con.prepareStatement(jdbc_insert_sql);
Sheet sheet = workbook.getSheetAt(0);
Row row;
System.out.println("last row number is========="+sheet.getLastRowNum());
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
row = sheet.getRow(i);
int empId = (int) (row.getCell(0).getNumericCellValue());
String empName = row.getCell(1).getStringCellValue();
String empEmail = row.getCell(2).getStringCellValue();
String sql="insert into employee "+"values('"+empId+"','"+empName+"','"+empEmail+"')";
preStatement = (PreparedStatement) con.prepareStatement(sql);
preStatement.execute();
System.out.println("Records inserted.........."+i);
}
System.out.println("");
}
}
catch (Exception e)
{
out.println("Error");
}
`
public static void setExcelFile(String Path, String SheetName) throws IOException, InvalidFormatException {
try {
// Open the Excel file
FileInputStream ExcelFile = new FileInputStream(Path);
// Access the required test data sheet
ExcelWBook = new XSSFWorkbook("C:\\Users\\data.xlsx");
ExcelWSheet = ExcelWBook.getSheet(SheetName);
} catch (Exception e) {
throw (e);
}
}

converting csv to excel through java

I have to convert CSV to XLS format through Java POI since I am doing some manipulations with XLS sheets through POI. Below is my code:
File file = new File("C:\\abc.csv");
FileInputStream fin = null;
fin = new FileInputStream(file);
HSSFWorkbook workbook = new HSSFWorkbook(fin);
HSSFSheet firstSheet1 = workbook.getSheetAt(0);
Now I want to write a fuctions, lets say method name is convertcsvtoexcel which will accept the file obj and in return it will be give me converted XLS file that file will be stored in my C: drive with the name abcout.xls and later on I will be passing it to workbook as shown. I have tried the following code. Please advise how I can custoise it to make it fittable for my piece of code.
ArrayList arList = null;
ArrayList al = null;
String fName = "test.csv";
String thisLine;
int count = 0;
FileInputStream file = null;
file = new FileInputStream(new File("C:\\abc.csv"));
//FileInputStream fis = new FileInputStream(file);
DataInputStream myInput = new DataInputStream(file);
int i = 0;
arList = new ArrayList();
while ((thisLine = myInput.readLine()) != null) {
al = new ArrayList();
String strar[] = thisLine.split(",");
for (int j = 0; j < strar.length; j++) {
al.add(strar[j]);
}
arList.add(al);
System.out.println();
i++;
}
try {
HSSFWorkbook hwb = new HSSFWorkbook();
HSSFSheet sheet = hwb.createSheet("new sheet");
for (int k = 0; k < arList.size(); k++) {
ArrayList ardata = (ArrayList) arList.get(k);
HSSFRow row = sheet.createRow((short) 0 + k);
for (int p = 0; p < ardata.size(); p++) {
HSSFCell cell = row.createCell((short) p);
String data = ardata.get(p).toString();
if (data.startsWith("=")) {
cell.setCellType(Cell.CELL_TYPE_STRING);
data = data.replaceAll("\"", "");
data = data.replaceAll("=", "");
cell.setCellValue(data);
} else if (data.startsWith("\"")) {
data = data.replaceAll("\"", "");
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue(data);
} else {
data = data.replaceAll("\"", "");
cell.setCellType(Cell.CELL_TYPE_NUMERIC);
cell.setCellValue(data);
}
//*/
// cell.setCellValue(ardata.get(p).toString());
}
System.out.println();
}
FileOutputStream fileOut = new FileOutputStream("C:\\abcout.xls");
hwb.write(fileOut);
fileOut.close();
System.out.println("Your excel file has been generated");
} catch (Exception ex) {
ex.printStackTrace();
} //main method end
public static void csvToXLSX() {
try {
String csvFileAddress = "test.csv"; //csv file address
String xlsxFileAddress = "test.xlsx"; //xlsx file address
XSSFWorkbook workBook = new XSSFWorkbook();
XSSFSheet sheet = workBook.createSheet("sheet1");
String currentLine=null;
int RowNum=0;
BufferedReader br = new BufferedReader(new FileReader(csvFileAddress));
while ((currentLine = br.readLine()) != null) {
String str[] = currentLine.split(",");
RowNum++;
XSSFRow currentRow=sheet.createRow(RowNum);
for(int i=0;i<str.length;i++){
currentRow.createCell(i).setCellValue(str[i]);
}
}
FileOutputStream fileOutputStream = new FileOutputStream(xlsxFileAddress);
workBook.write(fileOutputStream);
fileOutputStream.close();
System.out.println("Done");
} catch (Exception ex) {
System.out.println(ex.getMessage()+"Exception in try");
}
}

I have written a program in java to read data from MS excel sheet but it is showing that (The system cannot find the file specified)

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.

Categories