i have a document excel with textboxes
i want to create in this textboxes a text from java code
this is the code to get value , how i'm going to edit it using poid apache
try {
FileInputStream fsIP = new FileInputStream(new File("C:\\Book1.xls"));
// InputStream input = new FileInputStream("Book1.xls");
POIFSFileSystem fs = new POIFSFileSystem(fsIP);
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFPatriarch pat = sheet.getDrawingPatriarch();
List children = pat.getChildren();
Iterator it = children.iterator();
while (it.hasNext()) {
HSSFShape shape = (HSSFShape) it.next();
if (shape instanceof HSSFTextbox) {
shape.getAnchor()
HSSFTextbox textbox = (HSSFTextbox) shape;
HSSFRichTextString richString = textbox.getString();
String str = richString.getString();
System.out.println("String: " + str);
System.out.println("String length: " + str.length());
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
Related
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..
I'm converting CSV file to XLS file.
When I do the conversion, everything works perfect; however, when there's a comma inside the cell, it separates a column into two columns.
EX:
| Hello, World! | CSV FILE |
after conversion
| Hello | World! | CSV FILE | X --- What I get currently
| Hello, World! | CSV FILE | O --- What I want
String ab = thisLine.replaceAll(", ", " ");
Assuming everyone uses space after using a comma, replaceAll would work but this is not an ideal solution.
public void csv2excel(String csv) throws Exception
{
String inputCSVFile = csv + ".csv";
ArrayList arList=null;
ArrayList al=null;
String fName = inputCSVFile;
String thisLine;
int count=0;
FileInputStream fis = new FileInputStream(fName);
DataInputStream myInput = new DataInputStream(fis);
int i=0;
arList = new ArrayList();
while ((thisLine = myInput.readLine()) != null)
{
al = new ArrayList();
//String ab = thisLine.replaceAll(", ", " ");
//String strar[] ab.split(",");
String strar[] = thisLine.split(",");
//Here is where I split the columns.
for(int j=0;j<strar.length;j++)
{
al.add(strar[j]);
}
arList.add(al);
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(CellType.STRING);
data=data.replaceAll("\"", "");
data=data.replaceAll("=", "");
cell.setCellValue(data);
}else if(data.startsWith("\"")){
data=data.replaceAll("\"", "");
cell.setCellType(CellType.STRING);
cell.setCellValue(data);
}else{
data=data.replaceAll("\"", "");
cell.setCellType(CellType.NUMERIC);
cell.setCellValue(data);
}
//*/
// cell.setCellValue(ardata.get(p).toString());
}
}
FileOutputStream fileOut = new FileOutputStream(csv + ".xls");
hwb.write(fileOut);
fileOut.close();
} catch ( Exception ex ) {
ex.printStackTrace();
}
myInput.close();
fis.close();
}
I wonder if there's just a way to split column by column.
public void csv2excel(String csv) throws Exception
{
String inputCSVFile = csv + ".csv";
ArrayList arList=null;
ArrayList al=null;
String fName = inputCSVFile;
String thisLine;
int count=0;
FileInputStream fis = new FileInputStream(fName);
DataInputStream myInput = new DataInputStream(fis);
int i=0;
arList = new ArrayList();
while ((thisLine = myInput.readLine()) != null)
{
al = new ArrayList();
StringBuilder myLine = new StringBuilder(thisLine);
int lineLength = thisLine.length();
int bool = 0;
for (int k = 0; k < lineLength; k++)
{
if (thisLine.charAt(k) == '"')
{
bool++;
}
else if (thisLine.charAt(k) == ',' && bool % 2 != 0)
{
myLine.setCharAt(k, ' ');
}
}
//System.out.println(myLine);
//String ab = thisLine.replaceAll(", ", " ");
String strar[] = myLine.toString().split(",");
for(int j=0;j<strar.length;j++)
{
al.add(strar[j]);
}
arList.add(al);
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(CellType.STRING);
data=data.replaceAll("\"", "");
data=data.replaceAll("=", "");
cell.setCellValue(data);
}else if(data.startsWith("\"")){
data=data.replaceAll("\"", "");
cell.setCellType(CellType.STRING);
cell.setCellValue(data);
}else{
data=data.replaceAll("\"", "");
cell.setCellType(CellType.NUMERIC);
cell.setCellValue(data);
}
//*/
// cell.setCellValue(ardata.get(p).toString());
}
}
FileOutputStream fileOut = new FileOutputStream(csv + ".xls");
hwb.write(fileOut);
fileOut.close();
} catch ( Exception ex ) {
ex.printStackTrace();
}
myInput.close();
fis.close();
}
I coded to work around it...
Looks ugly, but works...
Would like to know if anyone has better answer.
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");
}
}
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.
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"));