The constructor XSSFWorkbook(FileInputStream) is undefined - java

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

Related

How to write to an existing formatted excel file in java

I'm trying to write some data inside an existing formatted excel file (.xls).
Inside this file I have 3 sheets and I have to put the data inside the table of the second sheet.
I tried this:
String filename = "Report.xls";
HSSFWorkbook workbook = new HSSFWorkbook();
FileOutputStream fileOut = null;
try {
fileOut = new FileOutputStream(filename);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
int numberOfSheets = workbook.getNumberOfSheets();
System.out.println("Sheets found: " + numberOfSheets);
for(int i=0; i<numberOfSheets; i++) {
HSSFSheet sheet = workbook.getSheetAt(i);
String sheetName= workbook.getSheetName(i);
System.out.println("\n\nSheet with index: " + i
+ "/nHas name: " + sheetName);
}
try {
workbook.write(fileOut);
//closing the Stream
fileOut.close();
//closing the workbook
workbook.close();
} catch (IOException e1) {
e1.printStackTrace();
}
The Excel file has 3 sheets but I get this output:
Sheets found: 0
So I tried this:
String filename = "Report.xls";
InputStream inputStream = null;
Workbook workbook = null;
OutputStream outputStream = null;
try {
inputStream = new FileInputStream(filename);
workbook = WorkbookFactory.create(inputStream);
int Num = workbook.getNumberOfSheets();
System.out.println("Sheets found: " + Num);
for (int i = 0; i < Num; i++) {
Sheet sheet = workbook.getSheetAt(i);
Sheet s = workbook.getSheetAt(i);
String sheetName= s.getSheetName();
System.out.println("The sheet found has name: " + sheetName);
}
} catch (Exception error) {
error.getMessage();
}
But I get the same output..

how to set the password to excel sheet using 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;
}

Data not getting saved after copying data from one sheet to another using java

I am using below code to copy couple of columns from one sheet to another in excel. But data is getting copied to new sheet but when i open that file and try to close it, it asks do you want to save it? What should i do.
FileInputStream fis;
try {
fis = new FileInputStream("C:\\Banks\\SBI.xlsx");
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet Sheet1 = wb.getSheet("new sheet");
XSSFSheet nfrntSheet = wb.createSheet("Original");
int n = Sheet1.getLastRowNum();
System.out.println(n);
for(int i = 0;i<n+11;i++)
{
XSSFRow r = nfrntSheet.createRow(i);
Cell c = r.createCell(0);
c.setCellFormula("'new sheet'!A"+(i-9));
nfrntSheet.autoSizeColumn(0);
}
for(int i = 0;i<n+11;i++)
{
XSSFRow r = nfrntSheet.getRow(i);
Cell c = r.createCell(1);
c.setCellFormula("'new sheet'!C"+(i-9));
nfrntSheet.autoSizeColumn(1);
}
for(int i = 0;i<=7;i++)
{
nfrntSheet.setColumnWidth(i, 5000);
}
nfrntSheet.setColumnWidth(1, 12000);
nfrntSheet.setColumnWidth(17, 30000);
fis.close();
FileOutputStream stream= new FileOutputStream(new File("C:\\Banks\\SBI.xlsx"));
wb.write(stream);
stream.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(CommandLineApp.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(CommandLineApp.class.getName()).log(Level.SEVERE, null, ex);
}

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

excel file not generating after UTF-8 encoding chosen

This part of my code was creating xls file successfuly
FileOutputStream fileOut = new FileOutputStream("c:\\Decrypted.xls");
wb.write(fileOut);
fileOut.close();
when other part of the code had this statement ( which was before the above code )
in = new ByteArrayInputStream(theCell_00.getBytes(""));
But when I changed it to
in = new ByteArrayInputStream(theCell_00.getBytes("UTF-8"));
this part
FileOutputStream fileOut = new FileOutputStream("c:\\Decrypted.xls");
wb.write(fileOut);
fileOut.close();
is not generating any xls file anymore.
I need to change the encoding to UTF-8 as I have done in ByteArrayInputStream line, so what should I do that the code still generates xls file.
In case you need it, the two parts are taken from this function.
public void getExcel() throws Exception {
try {
ByteArrayInputStream in = null;
FileOutputStream out = null;
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("new sheet");
/*
* KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128); SecretKey key =
* kgen.generateKey(); byte[] encoded = key.getEncoded();
*
* IOUtils.write(encoded, new FileOutputStream(new
* File("C:\\Users\\abc\\Desktop\\key.txt")));
*/
FileInputStream fin = new FileInputStream("C:\\key.txt");
DataInputStream din = new DataInputStream(fin);
byte b[] = new byte[16];
din.read(b);
InputStream excelResource = new FileInputStream(path);
Workbook rwb = Workbook.getWorkbook(excelResource);
int sheetCount = rwb.getNumberOfSheets();
Sheet rs = rwb.getSheet(0);
int rows = rs.getRows();
int cols = rs.getColumns();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < Col.length; j++) {
String theCell_00 = rs.getCell(j, i).getContents();
System.out.println("the Cell Content : " + theCell_00);
in = new ByteArrayInputStream(theCell_00.getBytes(""));
out = new FileOutputStream("c:\\Decrypted.txt");
try {
// System.out.println(b);
SecretKey key1 = new SecretKeySpec(b, "AES");
// Create encrypter/decrypter class
AESDecrypter encrypter = new AESDecrypter(key1);
encrypter.encrypt(new ByteArrayInputStream(theCell_00.getBytes()),
new FileOutputStream("temp.txt"));
// Decrypt
// encrypter.encrypt(,new FileOutputStream("Encrypted.txt"));
encrypter.decrypt(in, out);
try {
if (out != null)
out.close();
} finally {
if (in != null)
in.close();
}
// encrypter.decrypt(new
// ByteArrayInputStream(theCell_00.getBytes(Latin_1)),new
// FileOutputStream("c:\\Decrypted.txt"));
String filename = "c:\\Decrypted.txt";
BufferedReader bufferedReader = null;
try {
// Construct the BufferedReader object
bufferedReader = new BufferedReader(new FileReader(filename));
// System.out.println(bufferedReader.readLine());
String line = null;
while ((line = bufferedReader.readLine()) != null) {
// Process the data, here we just print it out
/*
* HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet =
* wb.createSheet("new sheet"); HSSFRow row = sheet.createRow(2);
*/
// System.out.println(i);
HSSFRow row = sheet.createRow(i);
int s_col = 0;
row.createCell(s_col).setCellValue(line);
// s_col++;
// row.createCell(1).setCellValue(new Date());
FileOutputStream fileOut = new FileOutputStream("c:\\Decrypted.xls");
wb.write(fileOut);
fileOut.close();
// System.out.println(line);
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
// Close the BufferedReader
try {
if (bufferedReader != null)
bufferedReader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
rwb.close();
} catch (Exception ex) {
ex.printStackTrace();
ex.getMessage();
}
}
What data types are expected by the call to AESDecrypter.decrypt? Does it have to take in a FileOutputStream object? Or can you pass in a Writer or other OutputStream?
I normally do something like this to write UTF-8 output:
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("c:\\Decrypted.txt"), "UTF-8"));

Categories