How to write to an existing formatted excel file in java - 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..

Related

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

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

Read the sheets of a zipped (.zip and .7z) excel file without saving it

I have to make a program in which the user can upload a zipped file(.7z or .zip). Now without a need to save this file I have to read its contents and check its extension. Till this point I have reached. Now if the file is a .xls file I want to pass this file to a 'HSSFWorkbook' object and check the contents of a particular sheet.
this is the code which I have written:
private void getNumberOfItemsInArchive(FormFile uploadedFile) throws Exception
{
File archiveFilename = new File(uploadedFile.getFileName());
OutputStream os = new FileOutputStream(archiveFilename);
InputStream is = new BufferedInputStream(uploadedFile.getInputStream());
int count;
byte buf[] = new byte[4096];
while ((count = is.read(buf)) > -1)
{
os.write(buf, 0, count);
}
RandomAccessFile randomAccessFile = null;
ISevenZipInArchive inArchive = null;
try
{
randomAccessFile = new RandomAccessFile(uploadedFile.getFileName(), "r");
logger.info("After generating randomAccessFile"+randomAccessFile);
inArchive = SevenZip.openInArchive(null, // autodetect archive type
new RandomAccessFileInStream(randomAccessFile));
ISimpleInArchive simpleInArchive = inArchive.getSimpleInterface();
logger.info("Count of items in archive: "+inArchive.getNumberOfItems());
logger.info("-----------------------------");
for (ISimpleInArchiveItem item : simpleInArchive.getArchiveItems())
{
String filename = item.getPath();
logger.info("Filename::"+filename);
String extension = filename.substring(filename.lastIndexOf(".") + 1, filename.length());
String excel = "xls";
if (extension.matches(excel) && inArchive.getNumberOfItems() == 1)
{
logger.info("Valid file");
// what should be written here?
read(??,"63","247");
}
else
{
logger.info("Invalid File");
}
}
.
.
.
.
}
public boolean read(FileInputStream inputFile,String appid,String templateid) throws IOException
{
logger.info("Inside Excel reader class"+ inputFile);
.
.
.
if(versionFlag.equals("true"))
{
try
{
// code needed for here
HSSFWorkbook workBook = new HSSFWorkbook(inputFile);
logger.info("the file path in work book is"+workBook);
int numberOfSheets=workBook.getNumberOfSheets();
logger.info("the number of sheets are"+numberOfSheets);
HSSFSheet newSheet=workBook.getSheet("VersionDetails");
if(newSheet==null)
{
result=false;
}
logger.info("the file path in newsheet is"+newSheet);
//int y=newSheet.getPhysicalNumberOfRows();
HSSFRow row=newSheet.getRow(17);
int numberofcell=row.getPhysicalNumberOfCells();
.
.
.
}
}
if you are talking about reading xls file, this can help :
try {
FileInputStream file = new FileInputStream(new File("C:\\test.xls"));
//Get the workbook instance for XLS file
HSSFWorkbook workbook = new HSSFWorkbook(file);
//Get first sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(0);
//Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()) {
Row row = rowIterator.next();
//For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch(cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t\t");
break;
}
}
System.out.println("");
}
file.close();
FileOutputStream out =
new FileOutputStream(new File("C:\\test.xls"));
workbook.write(out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
and you can validate the data within the xls in the switch case mentioned

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