Adding data to an Excel file using jxl - java

I'm creating an excel file using jxl. At first is should contain only some formatting and information about styles. Then, it should be updated every time someone adds new data to it.
public class WriteExcel {
private static WritableWorkbook workbook;
private static WritableCellFormat timesStandard;
private String inputFile;
final private static int FONT_SIZE = 12;
public void setOutputFile(String inputFile) {
this.inputFile = inputFile;
}
private void prepareSheet(WritableSheet sheet) throws WriteException {
sheet.mergeCells(0, 0, 1, 0);
sheet.mergeCells(3, 0, 4, 0);
sheet.mergeCells(6, 0, 7, 0);
WritableFont times12pt = new WritableFont(WritableFont.TIMES, FONT_SIZE);
timesStandard = new WritableCellFormat(times12pt);
CellView cv = new CellView();
cv.setFormat(timesStandard);
}
public void write() throws IOException, WriteException {
File file = new File(inputFile);
WorkbookSettings wbSettings = new WorkbookSettings();
wbSettings.setLocale(new Locale("en", "EN"));
WritableWorkbook workbook = Workbook.createWorkbook(file, wbSettings);
workbook.createSheet("First", 0);
WritableSheet excelSheet = workbook.getSheet(0);
prepareSheet(excelSheet);
workbook.write();
workbook.close();
}
public static void main(String[] args) throws WriteException, IOException {
WriteExcel test = new WriteExcel();
test.setOutputFile("c:/Users/H/Desktop/test.xls");
test.write();
}
}
I understand that I need another class that would let me access the file and add some data to it:
class Modify {
private static Logger logger = Logger.getLogger(Modify.class);
private File inputWorkbook;
private File outputWorkbook;
public Modify(String input, String output) {
inputWorkbook = new File(input);
outputWorkbook = new File(output);
logger.info("Input file: " + input);
logger.info("Output file: " + output);
}
public void readWrite() throws IOException, BiffException, WriteException {
logger.info("Reading...");
Workbook w1 = Workbook.getWorkbook(inputWorkbook);
logger.info("Copying...");
WritableWorkbook w2 = Workbook.createWorkbook(outputWorkbook, w1);
if (inputWorkbook.getName().equals("test.xls")) {
modify(w2);
}
w2.write();
w2.close();
logger.info("Done");
}
private void modify(WritableWorkbook w) throws WriteException {
logger.info("Modifying...");
WritableSheet sheet = w.getSheet("First");
//createContent(sheet); // contains methods responsible for adding data, for example:
addNumber(sheet, cols, rows, 2);
private static void addNumber(WritableSheet sheet, int column, int row, double d) throws WriteException, RowsExceededException {
Number number;
number = new Number(column, row, d, timesStandard);
sheet.addCell(number);
}
}
But I end up with a blank Excel file with the merged cells only.
How do I introduce the modifications?

Since you're manipulating a WritableWorkbook object which is not a member of your class for w2, shouldn't you have your modify() method not be void but instead return a WritableWorkbook ?
As I see it, a new one is instanciated when you call modify() but all changes at the end are dropped due to scope.
In the end you'll get something like
private WritableWorkbook modify(WritableWorkbook w) throws WriteException {
logger.info("Modifying...");
WritableSheet sheet = w.getSheet("First");
//createContent(sheet); // contains methods responsible for adding data, for example:
addNumber(sheet, cols, rows, 2);
return sheet;
}
quite basically. And a similar modification for addNumber seems in order too.
Then the respective calls would be sheet = addNumber(sheet, cols, rows, 2); and w2 = modify(w2);

Related

Problems to read a PDF with iText7 (work with iText5)

Here is the code to read a PDF with iText5, and it works :
public class CreateTOC {
public static final String SRC = "file.pdf";
class FontRenderFilter extends RenderFilter {
public boolean allowText(TextRenderInfo renderInfo) {
String font = renderInfo.getFont().getPostscriptFontName();
return font.endsWith("Bold") || font.endsWith("Oblique");
}
}
public static void main(String[] args) throws IOException, DocumentException {
new CreateTOC().parse(SRC);
}
public void parse(String filename) throws IOException {
PdfReader reader = new PdfReader(filename);
Rectangle rect = new Rectangle(1000, 1000);
RenderFilter regionFilter = new RegionTextRenderFilter(rect);
FontRenderFilter fontFilter = new FontRenderFilter();
TextExtractionStrategy strategy = new FilteredTextRenderListener(
new LocationTextExtractionStrategy(), regionFilter, fontFilter);
System.out.println(PdfTextExtractor.getTextFromPage(reader, 56, strategy));
reader.close();
}
}
Can someone help me to do it working in iText7 ? There are problems with the Rectangle and the TextExtractionStrategy (it's not the same constructor as iText5)
Edit : RenderFilter isn't available in iText7...

Exporting automated value to excel file in java

I am using selenium webdriver in eclipse with Java for a project at work. I am in need of exporting a value to an excel file. I am able to write to an excel file but am unable to export the specific value to the excel file.
Here is the automation process for getting the value:
public void AbbeyNational (String AbbeyNationalURL, String AN_AccCookiesButton, String AN_MortgageTabButton, String AN_ExistingCustomerButton, String AN_FollowRateButton, String AN_SVRButton, String AN_RateFld)throws InterruptedException {
driver.get(AbbeyNationalURL);
driver.findElement(By.xpath(AN_AccCookiesButton)).click();
driver.findElement(By.linkText(AN_MortgageTabButton)).click();
driver.findElement(By.xpath(AN_ExistingCustomerButton)).click();
driver.findElement(By.xpath(AN_FollowRateButton)).click();
driver.findElement(By.xpath(AN_SVRButton)).click();
String a = driver.findElement(By.cssSelector(AN_RateFld)).getText();
String AN_Rate = a.substring(54,58);
System.out.println(AN_Rate);
}
The 'AN_Rate' variable holds the value after automation.
The value prints to the console but I need the value to be exported to the excel file with the use of automation. Can anyone help me with this?
Additionally, here is my code for writing to an excel file:
public void writeToExcel(String AN_Rate) throws IOException{
File file = new File(filePath+"\\"+fileName);
XSSFWorkbook IRWorkbook = new XSSFWorkbook();
XSSFSheet Sheet0 = IRWorkbook.createSheet();
Sheet0.createRow(0).createCell(0).setCellValue(AN_Rate);
try {
FileOutputStream fos = new FileOutputStream(file);
IRWorkbook.write(fos);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
you can use this code for large set of data :
public class ExcelWriter {
// LinkedHashMap to maintain the insertion order
public static Map<String, String> dataMap = new LinkedHashMap<>();
public static String filePath = "D:\\ECLIPSE-WORKSPACE\\playground\\src\\main\\resources";
public static String fileName = "demo-data";
public static void main(String[] args) throws IOException {
String AN_Rate = "Data-1";
String BN_Rate = "Data-2";
String CN_Rate = "Data-3";
dataMap.put("AN_Rate", AN_Rate);
dataMap.put("BN_Rate", BN_Rate);
dataMap.put("CN_Rate", CN_Rate);
writeToExcel(dataMap, filePath, fileName);
}
public static void writeToExcel(Map<String, String> dataMap, String filePath, String fileName) throws IOException {
File file = new File(filePath + "\\" + fileName + ".xlsx");
if (file.exists()) {
file.delete();
}
file.createNewFile();
XSSFWorkbook IRWorkbook = new XSSFWorkbook();
XSSFSheet sheet = IRWorkbook.createSheet();
List<String> headers = dataMap.keySet().stream().collect(Collectors.toList()); // all key values in a list
List<String> data = new ArrayList<>(dataMap.values()); // all data in a list
setHeadersAndFillData(sheet, headers, data); // filling excel sheet with headers and corresponding data
try {
FileOutputStream fos = new FileOutputStream(file);
IRWorkbook.write(fos);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void setHeadersAndFillData(XSSFSheet sheet, List<String> headers, List<String> data) {
int headersSize = headers.size();
int dataSize = headers.size();
Row headerRow = sheet.createRow(0);
Row dataRow = sheet.createRow(1);
setCells(headers, headersSize, headerRow);
setCells(data, dataSize, dataRow);
}
private static void setCells(List<String> cellData, int headersSize, Row row) {
for (int rn = 0; rn < headersSize; rn++) {
row.createCell(rn).setCellValue(cellData.get(rn));
}
}
}
Just edit your method writeToExcel with :
Replace :File file = new File(filePath+"\\"+fileName);
with added file extention
File file = new File(filePath+"\\"+fileName + ".xlsx");
and than the value will be exported to excel file.
And if there is large set of data than you should store all values in a static map and than export all values to excel at once.

Writing to xls using POI for huge data and creating new workbook if neede [duplicate]

This question already has answers here:
Writing a large resultset to an Excel file using POI
(7 answers)
Closed 8 years ago.
I have code to Write to xls file usng POI but I am getting input for which we may get lacs of rows,hence it may exceed the max size of the workbook.
In that case I need to write the data to a new workbook and continue doing this everytime data exhausts the workbook size.My questions:
1) How do I come to know when a workbook is exhausted
2) how should I crate a new file
3)where should I keep my data while I track the no. of xls's.
Thanks!
If the input data is exceeding the max size of the workbook, you can use Big Grid Demo style for writing the data to the workbook. This will allow you to write unlimited data to the workbook.
/**
*
* #param zipfile the template file
* #param sheets the Map with
* key "name of the sheet entry to substitute
* (e.g. xl/worksheets/sheet1.xml, xl/worksheets/sheet2.xml etc)"
* and value "XML file with the sheet data"
* #param out the stream to write the result to
*/
private static void substitute(File zipfile, Map<String, File> sheets, OutputStream out) throws IOException {
ZipFile zip = new ZipFile(zipfile);
ZipOutputStream zos = new ZipOutputStream(out);
#SuppressWarnings("unchecked")
Enumeration<ZipEntry> en = (Enumeration<ZipEntry>) zip.entries();
while (en.hasMoreElements()) {
ZipEntry ze = en.nextElement();
if(!sheets.containsKey(ze.getName())){
zos.putNextEntry(new ZipEntry(ze.getName()));
InputStream is = zip.getInputStream(ze);
copyStream(is, zos);
is.close();
}
}
for (Map.Entry<String, File> entry : sheets.entrySet()) {
// System.out.println("Key -->"+entry.getKey());
zos.putNextEntry(new ZipEntry(entry.getKey()));
InputStream is = new FileInputStream(entry.getValue());
copyStream(is, zos);
is.close();
}
zos.close();
}
private static void copyStream(InputStream in, OutputStream out) throws IOException {
byte[] chunk = new byte[1024];
int count;
while ((count = in.read(chunk)) >=0 ) {
out.write(chunk,0,count);
}
}
/**
* Writes spreadsheet data in a Writer.
* (YK: in future it may evolve in a full-featured API for streaming data in Excel)
*/
public static class SpreadsheetWriter {
private final Writer _out;
private int _rownum;
public SpreadsheetWriter(Writer out){
_out = out;
}
public void beginSheet() throws IOException {
_out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<worksheet xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\">" );
_out.write("<sheetData>\n");
}
public void endSheet() throws IOException {
_out.write("</sheetData>");
_out.write("</worksheet>");
}
/**
* Insert a new row
*
* #param rownum 0-based row number
*/
public void insertRow(int rownum) throws IOException {
_out.write("<row r=\""+(rownum+1)+"\">\n");
this._rownum = rownum;
}
/**
* Insert row end marker
*/
public void endRow() throws IOException {
_out.write("</row>\n");
}
public void createCell(int columnIndex, String value, int styleIndex) throws IOException {
String ref = new CellReference(_rownum, columnIndex).formatAsString();
_out.write("<c r=\""+ref+"\" t=\"inlineStr\"");
if(styleIndex != -1) _out.write(" s=\""+styleIndex+"\"");
_out.write(">");
_out.write("<is><t>"+value+"</t></is>");
_out.write("</c>");
}
public void createCell(int columnIndex, String value) throws IOException {
createCell(columnIndex, value, -1);
}
public void createCell(int columnIndex, double value, int styleIndex) throws IOException {
String ref = new CellReference(_rownum, columnIndex).formatAsString();
_out.write("<c r=\""+ref+"\" t=\"n\"");
if(styleIndex != -1) _out.write(" s=\""+styleIndex+"\"");
_out.write(">");
_out.write("<v>"+value+"</v>");
_out.write("</c>");
}
public void createCell(int columnIndex, double value) throws IOException {
createCell(columnIndex, value, -1);
}
public void createCell(int columnIndex, Calendar value, int styleIndex) throws IOException {
createCell(columnIndex, DateUtil.getExcelDate(value, false), styleIndex);
}
}
You just need to call substitute() method while writing the data to the workbook,
ServletOutputStream out = null;
out = response.getOutputStream();
substitute(new File("template.xlsm"), sheets, out);
out.flush();
out.close();

how to send an excel file with servlet

im trying to create an excel file on a servlet and send it to the client browser when i did it on a stand alone program the file was created on my computer but when i tried to do it on a servlet it did nothing
servlet:
response.setContentType("text/html;charset=UTF-8");
// PrintWriter out = response.getWriter();
String[] items=request.getParameterValues("lecture");
String course=request.getParameter("course");
int sheets=Integer.parseInt(request.getParameter("sheets"));
List <XlElement> xlElements=getAllElements(items);
ServletOutputStream output=response.getOutputStream();
try
{
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename="+course+".xls");
CreateXl xl=new CreateXl();
xl.createScadualFile(output, xlElements, sheets);
output.println(course);
}
catch (Exception e)
{
System.out.println(e.toString());
throw new ServletException("Exception in Excel Sample Servlet", e);
}
output.close();
createXl class
private List<WritableSheet> xlSheets;
private String[] days={"א","ב","ג","ד","ה"};
private final int numOfClasses=9;
private final int cellHeight= 1020;
private final int cellWidth=15;
public void createScadualFile(ServletOutputStream output, List <XlElement> items,int sheets) throws IOException, WriteException{
xlSheets=new ArrayList<WritableSheet>();
WritableWorkbook workbook = Workbook.createWorkbook(output);
for(int i=0;i<sheets;i++){
WritableSheet sheet = workbook.createSheet("week "+(i+1), i);
xlSheets.add(sheet);
}
for(WritableSheet s: xlSheets){
initSheet(s);
}
for(XlElement e: items){
insertElement(e);
}
workbook.write();
workbook.close();
}
private WritableCellFormat getCellFormat(Colour colour, Pattern pattern) throws WriteException {
WritableFont cellFont = new WritableFont(WritableFont.TIMES, 12);
WritableCellFormat cellFormat = new WritableCellFormat(cellFont);
cellFormat.setBackground(colour, pattern);
cellFormat.setWrap(true);
cellFormat.setVerticalAlignment(jxl.format.VerticalAlignment.TOP);
return cellFormat;
}
private void initSheet(WritableSheet s) throws WriteException{
for(int i=0;i<days.length;i++){
Label l=new Label(i+1,0,days[i],getCellFormat(Colour.GREY_25_PERCENT,Pattern.SOLID));
s.setColumnView(i+1,cellWidth );
s.addCell(l);
}
for(int i=0;i<numOfClasses;i++){
Label l=new Label(0,i+1,Integer.toString(i+1),getCellFormat(Colour.GREY_25_PERCENT,Pattern.SOLID));
s.setRowView(i+1, cellHeight);
s.addCell(l);
}
}
private void insertElement(XlElement e) throws WriteException{
Label l=new Label(e.getCol(),e.getRow(),e.toXlString(), getCellFormat(Colour.RED,Pattern.SOLID));
xlSheets.get(e.getWeek()).mergeCells(e.getCol(), e.getRow(), e.getCol(), e.getRow()+e.getSpan()-1);
xlSheets.get(e.getWeek()).addCell(l);
}
dose anybody know what I am doing wrong?
First, you should only call response.setContentType() once. You want to return an Excel, so take out the one where you are setting the content type to "text/html;charset=UTF-8".
Second, writing text to the output stream after writing the binary file to it will screw it up. Take out the output.println(course);
Third, I really don't think the output.close(); is needed either, so you might try taking that out as well.

Java List to Excel Columns

Correct me where I'm going wrong.
I'm have written a program in Java which will get list of files from two different directories and make two (Java list) with the file names. I want to transfer the both the list (downloaded files list and Uploaded files list) to an excel.
What the result i'm getting is those list are transferred row wise. I want them in column wise.
Given below is the code:
public class F {
static List<String> downloadList = new ArrayList<>();
static List<String> dispatchList = new ArrayList<>();
public static class FileVisitor extends SimpleFileVisitor<Path> {
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
String name = file.toRealPath().getFileName().toString();
if (name.endsWith(".pdf") || name.endsWith(".zip")) {
downloadList.add(name);
}
if (name.endsWith(".xml")) {
dispatchList.add(name);
}
return FileVisitResult.CONTINUE;
}
}
public static void main(String[] args) throws IOException {
try {
Path downloadPath = Paths.get("E:\\report\\02_Download\\10252013");
Path dispatchPath = Paths.get("E:\\report\\01_Dispatch\\10252013");
FileVisitor visitor = new FileVisitor();
Files.walkFileTree(downloadPath, visitor);
Files.walkFileTree(downloadPath, EnumSet.of(FileVisitOption.FOLLOW_LINKS), 1, visitor);
Files.walkFileTree(dispatchPath, visitor);
Files.walkFileTree(dispatchPath, EnumSet.of(FileVisitOption.FOLLOW_LINKS), 1, visitor);
System.out.println("Download File List" + downloadList);
System.out.println("Dispatch File List" + dispatchList);
F f = new F();
f.UpDown(downloadList, dispatchList);
} catch (Exception ex) {
Logger.getLogger(F.class.getName()).log(Level.SEVERE, null, ex);
}
}
int rownum = 0;
int colnum = 0;
HSSFSheet firstSheet;
Collection<File> files;
HSSFWorkbook workbook;
File exactFile;
{
workbook = new HSSFWorkbook();
firstSheet = workbook.createSheet("10252013");
Row headerRow = firstSheet.createRow(rownum);
headerRow.setHeightInPoints(40);
}
public void UpDown(List<String> download, List<String> upload) throws Exception {
List<String> headerRow = new ArrayList<>();
headerRow.add("Downloaded");
headerRow.add("Uploaded");
List<List> recordToAdd = new ArrayList<>();
recordToAdd.add(headerRow);
recordToAdd.add(download);
recordToAdd.add(upload);
F f = new F();
f.CreateExcelFile(recordToAdd);
f.createExcelFile();
}
void createExcelFile() {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File("E:\\report\\Download&Upload.xls"));
HSSFCellStyle hsfstyle = workbook.createCellStyle();
hsfstyle.setBorderBottom((short) 1);
hsfstyle.setFillBackgroundColor((short) 245);
workbook.write(fos);
} catch (Exception e) {
}
}
public void CreateExcelFile(List<List> l1) throws Exception {
try {
for (int j = 0; j < l1.size(); j++) {
Row row = firstSheet.createRow(rownum);
List<String> l2 = l1.get(j);
for (int k = 0; k < l2.size(); k++) {
Cell cell = row.createCell(k);
cell.setCellValue(l2.get(k));
}
rownum++;
}
} catch (Exception e) {
} finally {
}
}
}
(The purpose is to verify the files Downloaded and Uploaded for the given date)
Thanks.
If you want to access/build the worksheet in columns instead of rows, you need to change the worksheet accessing code.
Snipped out from your existing code, here are the key functions:
Row row = firstSheet.createRow( rowNum);
Cell cell = row.createCell( colNum);
cell.setCellValue( value);
You need to rearrange those loops to output your data in a column-wise fashion.
Thanks for the suggestions.. I have modified my program and uploaded with the solution.
public class F {
static List<String> downloadList = new ArrayList<>();
static List<String> dispatchList = new ArrayList<>();
public static class FileVisitor extends SimpleFileVisitor<Path> {
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
String name = file.toRealPath().getFileName().toString();
if (name.endsWith(".pdf") || name.endsWith(".zip")) {
downloadList.add(name);
}
if (name.endsWith(".xml")) {
dispatchList.add(name);
}
return FileVisitResult.CONTINUE;
}
}
public static void main(String[] args) throws IOException {
try {
Path downloadPath = Paths.get("E:\\Download\\10292013");
Path dispatchPath = Paths.get("E:\\Dispatch\\10292013");
FileVisitor visitor = new FileVisitor();
Files.walkFileTree(downloadPath, visitor);
Files.walkFileTree(downloadPath, EnumSet.of(FileVisitOption.FOLLOW_LINKS), 1, visitor);
Files.walkFileTree(dispatchPath, visitor);
Files.walkFileTree(dispatchPath, EnumSet.of(FileVisitOption.FOLLOW_LINKS), 1, visitor);
/* List all files*/
System.out.println("Download File List" + downloadList);
System.out.println("Dispatch File List" + dispatchList);
F f = new F();
f.UpDown(downloadList, dispatchList);
} catch (Exception ex) {
Logger.getLogger(F.class.getName()).log(Level.SEVERE, null, ex);
}
}
int rownum = 0;
int colnum = 0;
HSSFSheet firstSheet;
Collection<File> files;
HSSFWorkbook workbook;
File exactFile;
{
workbook = new HSSFWorkbook();
firstSheet = workbook.createSheet("10292013");
Row headerRow = firstSheet.createRow(rownum);
headerRow.setHeightInPoints(40);
}
public void UpDown(List<String> download, List<String> upload) throws Exception {
List<String> headerRow = new ArrayList<String>();
headerRow.add("Downloaded");
headerRow.add("Uploaded");
List<List<String>> recordToAdd = new ArrayList<List<String>>();
recordToAdd.add(headerRow);
recordToAdd.add(download);
recordToAdd.add(upload);
CreateExcelFile(headerRow, download, upload);
createExcelFile();
}
void createExcelFile() {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File("E:\\report\\Download&Upload.xls"));
HSSFCellStyle hsfstyle = workbook.createCellStyle();
hsfstyle.setBorderBottom((short) 1);
hsfstyle.setFillBackgroundColor((short) 245);
workbook.write(fos);
} catch (Exception e) {
}
}
public void CreateExcelFile(List<String> headers, List<String> down, List<String> up) throws Exception {
try {
Row row = firstSheet.createRow((short)(rownum++));
for(int i = 0;i < headers.size();i++) {
Cell cell = row.createCell(i);
cell.setCellValue(headers.get(i));
}
for (int j = 0; j < down.size(); j++) {
row = firstSheet.createRow((short)(rownum++));
Cell cell = row.createCell(0);
cell.setCellValue(down.get(j));
if(up.size() > j) {
cell = row.createCell(1);
cell.setCellValue(up.get(j));
}
}
} catch (Exception e) {
} finally {
}
}
}

Categories