I need to embed files
(.ppt(x), .doc(x), .jpg, .txt,...)
in excel (format xlsx) using Java Apache POI.
I have found an example to embed files in excel (format xls) using
POI-HSSF
(Embed files into Excel using Apache POI),
but this example does not work with excel xlsx format.
Does somebody know if it is possible to do this using POI-XSSF ?
'try this it works for me...' use this jars to run this code.....
1) poi-3.13-20150929.jar
2) poi-ooxml-3.13-20150929.jar
3) poi-ooxml-schemas-3.13-20150929.jar
public String getReport() throws RecordNotFoundException{
ResultSet rs = null;
ResultSet rs1 = null;
Connection conn = null;
CallableStatement cstm = null;
PreparedStatement pstmt = null;
try {
HttpServletRequest request;
HttpSession session;
request = (HttpServletRequest) ActionContext.getContext().get(
"com.opensymphony.xwork2.dispatcher.HttpServletRequest");
session = request.getSession();
conn = JndiConnection.getOracleConnection();
String sReportName = "";
ArrayList<String> mainData = new ArrayList<String>();
conn = JndiConnection.getOracleConnection();
cstm = conn.prepareCall("your procedure name");
cstm.setString(1, first parameter);
cstm.setString(2, second parameter);
cstm.registerOutParameter(3, OracleTypes.CURSOR);
cstm.execute();
rs1 = (ResultSet) cstm.getObject(3);
ResultSetMetaData rsmd = rs1.getMetaData();
String sColumnData="Sr.No";
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
sColumnData+="~~" + rsmd.getColumnName(i);
}
String headerString=sColumnData.replace("Sr.No~~", "");
mainData.add(headerString);
while (rs1.next()) {
System.out.println("data...............::" + rs1.getString(1));
String sData = "data";
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
String column=rs1.getString(rsmd.getColumnName(i));
if (column == null) {
String finalData = "";
sData += "~~" + finalData;
} else {
sData += "~~" + rs1.getString(rsmd.getColumnName(i));
}
}
String bodyData=sData.replace("data~~", "");
mainData.add(bodyData);
System.out.println();
}
System.out.println("main data...............::" + mainData);
session.setAttribute("myReportData", mainData);
sReportName = genReport(mainData, title in file, "file path");
if (!"".equals(sReportName)) {
session.setAttribute("myReportDataExcelFile", sReportName);
}
setFileInputStream(new BufferedInputStream(new FileInputStream(sReportName)));
setFileName(new File(sReportName).getName());
} catch (SQLException se) {
throw new RecordNotFoundException(se);
} catch (NestableException ne) {
throw new RecordNotFoundException(ne);
} catch (Exception e) {
throw new RecordNotFoundException(e);
} finally {
try {
JndiConnection.freeConnections(cstm, conn, rs, rs1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return SUCCESS;
}"
'Above method will get the from database and put it into the list, now use bellow method
to write xls file with POI HSSF.'
private String genReport(ArrayList<String> arrDisplayDataList, String FileName, String sTitleName, String sPath)
throws Exception {
String fileNameWithPath;
Exception exception;
int col = 0;
int sno = 1;
fileNameWithPath = "";
String sFromate = "";
Connection con = null;
String ColumnDataList[] = null;
System.out.println("::::: Inside genReport() 2:::::");
try {
String[] arrColumnList = arrDisplayDataList.get(0).split("~~");
System.out.println("Length:::" + arrColumnList.length);
if (arrColumnList.length > 1) {
System.out.println("==Inside Of Record Data===");
DateFormat dateFormat = new SimpleDateFormat("ddMMyyyyHHmmss");
Calendar cal = Calendar.getInstance();
sFromate = dateFormat.format(cal.getTime());
FileName = (new StringBuilder()).append(FileName).append("_").append(sFromate).toString();
fileNameWithPath = (new StringBuilder()).append(sPath).append("/").append(FileName).append(".xls")
.toString();
File f1 = new File((new StringBuilder()).append(sPath).append("/").append(FileName).append(".xls")
.toString());
f1.getParentFile().mkdirs();
HSSFWorkbook wb = new HSSFWorkbook();
FileOutputStream fileOut = new FileOutputStream(f1);
HSSFSheet sheets = wb.createSheet("Sheet" + (sno++));
int row = 1;
HSSFRow rows;
if (row == 1) {
rows = sheets.createRow(0);
HSSFCell cells = rows.createCell(0);
cells.setCellType(1);
HSSFCellStyle cellStyle1 = wb.createCellStyle();
cellStyle1.setBorderBottom(HSSFCellStyle.BORDER_THIN);
cellStyle1.setBorderTop(HSSFCellStyle.BORDER_THIN);
cellStyle1.setBorderRight(HSSFCellStyle.BORDER_THIN);
cellStyle1.setBorderLeft(HSSFCellStyle.BORDER_THIN);
cells.setCellStyle(cellStyle1);
cells.setCellValue(sTitleName);
HSSFCellStyle cellStyle = wb.createCellStyle();
HSSFFont fontStyle = wb.createFont();
cellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
fontStyle.setColor(IndexedColors.BLACK.getIndex());
fontStyle.setBoldweight((short) 700);
fontStyle.setFontHeightInPoints((short) 12);
cellStyle.setFillPattern((short) 1);
cellStyle.setFont(fontStyle);
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER_SELECTION);
cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
cells.setCellStyle(cellStyle);
sheets.addMergedRegion(new CellRangeAddress(0, 0, 0, arrColumnList.length - 1));
for (int columnIndex = 0; columnIndex < 50; columnIndex++) {
sheets.autoSizeColumn(columnIndex);
}
}
rows = sheets.createRow(row++);
for (col = 0; col < arrColumnList.length; col++) {
HSSFCell cells = rows.createCell(col);
String sVal = (String) arrColumnList[col];
cells.setCellType(1);
cells.setCellValue(sVal);
HSSFCellStyle cellStyle = wb.createCellStyle();
HSSFFont fontStyle = wb.createFont();
fontStyle.setColor(IndexedColors.BLACK.getIndex());
fontStyle.setBoldweight((short) 700);
fontStyle.setFontHeightInPoints((short) 10);
cellStyle.setFont(fontStyle);
cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
cells.setCellStyle(cellStyle);
for (int columnIndex = 0; columnIndex < 100; columnIndex++) {
sheets.autoSizeColumn(columnIndex);
}
}
int rownum = 2;
int rowcount = 0;
for (int i = 1; i < arrDisplayDataList.size(); i++) {
if (rownum >= 65000) {
sheets = wb.createSheet("Sheet " + (sno++));
rownum = 0;
}
rows = sheets.createRow(rownum++);
String sData = ((String) arrDisplayDataList.get(i)).toString();
String sSplitData[] = sData.split("~~");
int xcount = 0;
for (col = 0; col < sSplitData.length; col++) {
HSSFCell cells = rows.createCell(xcount++);
String sVal = sSplitData[col];
if (sVal.equalsIgnoreCase("Total")) {
HSSFCellStyle cellStyle = wb.createCellStyle();
HSSFFont fontStyle = wb.createFont();
fontStyle.setColor(IndexedColors.BLACK.getIndex());
fontStyle.setBoldweight((short) 600);
fontStyle.setFontHeightInPoints((short) 12);
cellStyle.setFont(fontStyle);
cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
// cells.setCellStyle(cellStyle);
cells.setCellType(1);
for (int k = 3; k < rows.getLastCellNum(); k++) {// For
// each
// cell
// in
// the
// row
rows.getCell(k).setCellStyle(cellStyle);// Set
// the
// sty;e
}
cells.setCellValue(sVal);
System.out.println("TTT:" + sVal);
} else {
/*
* HSSFCellStyle cellStyle = wb.createCellStyle();
* cellStyle
* .setBorderBottom(HSSFCellStyle.BORDER_THIN);
* cellStyle
* .setBorderTop(HSSFCellStyle.BORDER_THIN);
* cellStyle
* .setBorderRight(HSSFCellStyle.BORDER_THIN);
* cellStyle
* .setBorderLeft(HSSFCellStyle.BORDER_THIN);
* //cells.setCellStyle(cellStyle);
* cells.setCellType(1);
*/
cells.setCellValue(sVal);
}
}
}
wb.write(fileOut);
fileOut.close();
} else {
fileNameWithPath = "NO RECORD FOUND";
}
} catch (Exception e) {
System.out.println("Exception ::::" + e);
e.printStackTrace();
throw e;
}
return fileNameWithPath;
}
Related
I want to write multiple data in excel with column name like TestCol and TestCol1.
Same data store in excel, now want to read either TestCol or TestCol1.
Xls_reader reader = new Xls_reader();
reader.Xls_Reader("C:uat\testdata\FreeCMSTestData.xlsx");
reader.addSheet("TestData");
reader.addColumn("TestData", "TestCol");
reader.addColumn("TestData", "TestCol1");
int n=3;
for(int i=2;i<n;i++)
{
reader.setCellData("TestData", "TestCol", i, str1);
reader.setCellData("TestData", "TestCol1", i, part);
}
Now, Data is not going in respective Column one below the other instead it get add to the adjacent.
public class Xls_reader {
public String path;
public FileInputStream fis = null;
public FileOutputStream fileOut = null;
private XSSFWorkbook workbook = null;
private XSSFSheet sheet = null;
private XSSFRow row = null;
private XSSFCell cell = null;
public void Xls_Reader(String path) {
this.path = path;
try {
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);
sheet = workbook.getSheetAt(0);
fis.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// returns the row count in a sheet
public int getRowCount(String sheetName) {
int index = workbook.getSheetIndex(sheetName);
if (index == -1)
return 0;
else {
sheet = workbook.getSheetAt(index);
int number = sheet.getLastRowNum() + 1;
return number;
}
}
// returns the data from a cell
public String getCellData(String sheetName, String colName, int rowNum) {
try {
if (rowNum <= 0)
return "";
int index = workbook.getSheetIndex(sheetName);
int col_Num = -1;
if (index == -1)
return "";
sheet = workbook.getSheetAt(index);
row = sheet.getRow(0);
for (int i = 0; i < row.getLastCellNum(); i++) {
// System.out.println(row.getCell(i).getStringCellValue().trim());
if (row.getCell(i).getStringCellValue().trim().equals(colName.trim()))
col_Num = i;
}
if (col_Num == -1)
return "";
sheet = workbook.getSheetAt(index);
row = sheet.getRow(rowNum - 1);
if (row == null)
return "";
cell = row.getCell(col_Num);
if (cell == null)
return "";
// System.out.println(cell.getCellType());
if (cell.getCellType() == Cell.CELL_TYPE_STRING)
return cell.getStringCellValue();
else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC || cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
String cellText = String.valueOf(cell.getNumericCellValue());
if (HSSFDateUtil.isCellDateFormatted(cell)) {
// format in form of M/D/YY
double d = cell.getNumericCellValue();
Calendar cal = Calendar.getInstance();
cal.setTime(HSSFDateUtil.getJavaDate(d));
cellText = (String.valueOf(cal.get(Calendar.YEAR))).substring(2);
cellText = cal.get(Calendar.DAY_OF_MONTH) + "/" + cal.get(Calendar.MONTH) + 1 + "/" + cellText;
// System.out.println(cellText);
}
return cellText;
} else if (cell.getCellType() == Cell.CELL_TYPE_BLANK)
return "";
else
return String.valueOf(cell.getBooleanCellValue());
} catch (Exception e) {
e.printStackTrace();
return "row " + rowNum + " or column " + colName + " does not exist in xls";
}
}
// returns the data from a cell
public String getCellData(String sheetName, int colNum, int rowNum) {
try {
if (rowNum <= 0)
return "";
int index = workbook.getSheetIndex(sheetName);
if (index == -1)
return "";
sheet = workbook.getSheetAt(index);
row = sheet.getRow(rowNum - 1);
if (row == null)
return "";
cell = row.getCell(colNum);
if (cell == null)
return "";
if (cell.getCellType() == Cell.CELL_TYPE_STRING)
return cell.getStringCellValue();
else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC || cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
String cellText = String.valueOf(cell.getNumericCellValue());
if (HSSFDateUtil.isCellDateFormatted(cell)) {
// format in form of M/D/YY
double d = cell.getNumericCellValue();
Calendar cal = Calendar.getInstance();
cal.setTime(HSSFDateUtil.getJavaDate(d));
cellText = (String.valueOf(cal.get(Calendar.YEAR))).substring(2);
cellText = cal.get(Calendar.MONTH) + 1 + "/" + cal.get(Calendar.DAY_OF_MONTH) + "/" + cellText;
// System.out.println(cellText);
}
return cellText;
} else if (cell.getCellType() == Cell.CELL_TYPE_BLANK)
return "";
else
return String.valueOf(cell.getBooleanCellValue());
} catch (Exception e) {
e.printStackTrace();
return "row " + rowNum + " or column " + colNum + " does not exist in xls";
}
}
// returns true if data is set successfully else false
public boolean setCellData(String sheetName, String colName, int rowNum, String data) {
try {
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);
if (rowNum <= 0)
return false;
int index = workbook.getSheetIndex(sheetName);
int colNum = -1;
if (index == -1)
return false;
sheet = workbook.getSheetAt(index);
row = sheet.getRow(0);
for (int i = 0; i < row.getLastCellNum(); i++) {
// System.out.println(row.getCell(i).getStringCellValue().trim());
if (row.getCell(i).getStringCellValue().trim().equals(colName))
colNum = i;
}
if (colNum == -1)
return false;
sheet.autoSizeColumn(colNum);
row = sheet.getRow(rowNum - 1);
if (row == null)
row = sheet.createRow(rowNum - 1);
cell = row.getCell(colNum);
if (cell == null)
cell = row.createCell(colNum);
// cell style
// CellStyle cs = workbook.createCellStyle();
// cs.setWrapText(true);
// cell.setCellStyle(cs);
cell.setCellValue(data);
fileOut = new FileOutputStream(path);
workbook.write(fileOut);
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
// returns true if data is set successfully else false
public boolean setCellData(String sheetName, String colName, int rowNum, String data, String url) {
// System.out.println("setCellData setCellData******************");
try {
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);
if (rowNum <= 0)
return false;
int index = workbook.getSheetIndex(sheetName);
int colNum = -1;
if (index == -1)
return false;
sheet = workbook.getSheetAt(index);
// System.out.println("A");
row = sheet.getRow(0);
for (int i = 0; i < row.getLastCellNum(); i++) {
// System.out.println(row.getCell(i).getStringCellValue().trim());
if (row.getCell(i).getStringCellValue().trim().equalsIgnoreCase(colName))
colNum = i;
}
if (colNum == -1)
return false;
sheet.autoSizeColumn(colNum); // ashish
row = sheet.getRow(rowNum - 1);
if (row == null)
row = sheet.createRow(rowNum - 1);
cell = row.getCell(colNum);
if (cell == null)
cell = row.createCell(colNum);
cell.setCellValue(data);
XSSFCreationHelper createHelper = workbook.getCreationHelper();
// cell style for hyperlinks
// by default hypelrinks are blue and underlined
CellStyle hlink_style = workbook.createCellStyle();
XSSFFont hlink_font = workbook.createFont();
hlink_font.setUnderline(XSSFFont.U_SINGLE);
hlink_font.setColor(IndexedColors.BLUE.getIndex());
hlink_style.setFont(hlink_font);
// hlink_style.setWrapText(true);
XSSFHyperlink link = createHelper.createHyperlink(XSSFHyperlink.LINK_FILE);
link.setAddress(url);
cell.setHyperlink(link);
cell.setCellStyle(hlink_style);
fileOut = new FileOutputStream(path);
workbook.write(fileOut);
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
// returns true if sheet is created successfully else false
public boolean addSheet(String sheetname) {
FileOutputStream fileOut;
try {
workbook.createSheet(sheetname);
fileOut = new FileOutputStream(path);
workbook.write(fileOut);
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
// returns true if sheet is removed successfully else false if sheet does
// not exist
public boolean removeSheet(String sheetName) {
int index = workbook.getSheetIndex(sheetName);
if (index == -1)
return false;
FileOutputStream fileOut;
try {
workbook.removeSheetAt(index);
fileOut = new FileOutputStream(path);
workbook.write(fileOut);
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
// returns true if column is created successfully
public boolean addColumn(String sheetName, String colName) {
// System.out.println("**************addColumn*********************");
try {
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);
int index = workbook.getSheetIndex(sheetName);
if (index == -1)
return false;
XSSFCellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(HSSFColor.GREY_40_PERCENT.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
sheet = workbook.getSheetAt(index);
row = sheet.getRow(0);
if (row == null)
row = sheet.createRow(0);
// cell = row.getCell();
// if (cell == null)
// System.out.println(row.getLastCellNum());
if (row.getLastCellNum() == -1)
cell = row.createCell(0);
else
cell = row.createCell(row.getLastCellNum());
cell.setCellValue(colName);
cell.setCellStyle(style);
fileOut = new FileOutputStream(path);
workbook.write(fileOut);
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
// removes a column and all the contents
public boolean removeColumn(String sheetName, int colNum) {
try {
if (!isSheetExist(sheetName))
return false;
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);
sheet = workbook.getSheet(sheetName);
XSSFCellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(HSSFColor.GREY_40_PERCENT.index);
XSSFCreationHelper createHelper = workbook.getCreationHelper();
style.setFillPattern(HSSFCellStyle.NO_FILL);
for (int i = 0; i < getRowCount(sheetName); i++) {
row = sheet.getRow(i);
if (row != null) {
cell = row.getCell(colNum);
if (cell != null) {
cell.setCellStyle(style);
row.removeCell(cell);
}
}
}
fileOut = new FileOutputStream(path);
workbook.write(fileOut);
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
// find whether sheets exists
public boolean isSheetExist(String sheetName) {
int index = workbook.getSheetIndex(sheetName);
if (index == -1) {
index = workbook.getSheetIndex(sheetName.toUpperCase());
if (index == -1)
return false;
else
return true;
} else
return true;
}
// returns number of columns in a sheet
public int getColumnCount(String sheetName) {
// check if sheet exists
if (!isSheetExist(sheetName))
return -1;
sheet = workbook.getSheet(sheetName);
row = sheet.getRow(0);
if (row == null)
return -1;
return row.getLastCellNum();
}
// String sheetName, String testCaseName,String keyword ,String URL,String
// message
public boolean addHyperLink(String sheetName, String screenShotColName, String testCaseName, int index, String url,
String message) {
// System.out.println("ADDING addHyperLink******************");
url = url.replace('\\', '/');
if (!isSheetExist(sheetName))
return false;
sheet = workbook.getSheet(sheetName);
for (int i = 2; i <= getRowCount(sheetName); i++) {
if (getCellData(sheetName, 0, i).equalsIgnoreCase(testCaseName)) {
// System.out.println("**caught "+(i+index));
setCellData(sheetName, screenShotColName, i + index, message, url);
break;
}
}
return true;
}
public int getCellRowNum(String sheetName, String colName, String cellValue) {
for (int i = 2; i <= getRowCount(sheetName); i++) {
if (getCellData(sheetName, colName, i).equalsIgnoreCase(cellValue)) {
return i;
}
}
return -1;
}
I have written the below Java code, which is executing fine in order to export the results in xlsx file from Oracle DB. But can someone help me to improve the performance of this code by which this below code can extract the result very fast.
Below is the Java Code which I have tried as of now; But it is slow while exporting result as compared to excel export from SQL Developer
public class FilesFromFolder {
private Workbook writeWorkbook;
public void ExportService(DBConnection con) {
writeWorkbook = new XSSFWorkbook();
Sheet desSheet = writeWorkbook.createSheet("Data");
Statement stmt = null;
ResultSet rs = null;
int columnsNumber = 0;
ResultSetMetaData rsmd = null;
FileOutputStream fileOut = null;
Connection cntn = null;
String filePath = "C:\\Users\\Desktop\\OracleExport";
File files = new File(filePath);
File[] file = files.listFiles();
String fileNameWithOutExt = null;
if (file != null) {
for (int i = 0; i < file.length; i++) {
if (file[i].isFile()) {
String tempFilename = file[i].getName();
fileNameWithOutExt = tempFilename.replaceFirst("[.][^.]+$", "");
File fileTemp = file[i];
try {
String fileContent = FileUtils.readFileToString(fileTemp, "UTF8");
// System.out.println(fileContent);
cntn = con.getConnection();
stmt = cntn.createStatement();
rs = stmt.executeQuery(fileContent);
rsmd = rs.getMetaData();
columnsNumber = rsmd.getColumnCount();
Row desRow1 = desSheet.createRow(0);
for (int col = 0; col < columnsNumber; col++) {
Cell newpath = desRow1.createCell(col);
newpath.setCellValue(rsmd.getColumnLabel(col + 1));
}
while (rs.next()) {
System.out.println("Row number -->" + rs.getRow());
Row desRow = desSheet.createRow(rs.getRow());
for (int col = 0; col < columnsNumber; col++) {
Cell newpath = desRow.createCell(col);
newpath.setCellValue(rs.getString(col + 1));
}
String outputFile = "C:\\Users\\Desktop\\OracleExport\\" + fileNameWithOutExt
+ ".xlsx";
fileOut = new FileOutputStream(outputFile);
writeWorkbook.write(fileOut);
}
System.out.println(fileNameWithOutExt + " export complete");
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (fileOut!= null) {
try {
fileOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (cntn != null) {
con.closeConnection();
}
}
}
}
}
}
}
I'am facing a wierd behaviours when creating excel spreadsheets with poi. I am able to save contents but when i open it on excel and try to close the document whitout touching it i get a messagebox with a message along the lines of "would you like to save your modifications".
code :
protected static Map< String ,CellStyle> makeCellStyles(XSSFWorkbook workbook) {
Map<String , CellStyle> styles = new HashMap<String , CellStyle>();
Font font = workbook.createFont();
CellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(IndexedColors.LAVENDER.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
font.setBold(true);
style.setFont(font);
style.setAlignment(CellStyle.ALIGN_CENTER);
style.setBorderTop(CellStyle.BORDER_MEDIUM);
style.setBorderLeft(CellStyle.BORDER_MEDIUM);
style.setBorderRight(CellStyle.BORDER_MEDIUM);
style.setBorderBottom(CellStyle.BORDER_MEDIUM);
styles.put("groupHeader", style);
style = workbook.createCellStyle();
font = workbook.createFont();
font.setColor(HSSFColor.WHITE.index);
font.setBold(true);
style.setBorderTop(CellStyle.BORDER_MEDIUM);
style.setBorderLeft(CellStyle.BORDER_MEDIUM);
style.setBorderRight(CellStyle.BORDER_MEDIUM);
style.setBorderBottom(CellStyle.BORDER_MEDIUM);
style.setFillForegroundColor(IndexedColors.BLUE_GREY.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
style.setFont(font);
styles.put("rowHeader", style);
DataFormat format = workbook.createDataFormat();
style = workbook.createCellStyle();
style.setBorderRight(CellStyle.BORDER_MEDIUM);
style.setDataFormat(format.getFormat("# ##0"));
style.setAlignment(CellStyle.ALIGN_CENTER);
styles.put("borderData", style);
style = workbook.createCellStyle();
//style.setBorderBottom(CellStyle.BORDER_MEDIUM);
style.setBorderRight(CellStyle.BORDER_MEDIUM);
style.setAlignment(CellStyle.ALIGN_CENTER);
style.setDataFormat(format.getFormat("# ##0"));
styles.put("data", style);
return styles;
}
static private void writeXls() {
// Using XSSF for xlsx format, for xls use HSSF
//final String FILE_PATH = "F:/lesStats.xlsx";
try {
FileOutputStream fos = new FileOutputStream(statfile);
XSSFWorkbook workbook = new XSSFWorkbook();
DataFormat format = workbook.createDataFormat();
String si = "Fichier;total documents; documents corrects;"
+ "documents erronnees; erreurs formats ; "
+ "erreur dictionnaire ; erreurs index manquants ; erreurs chemin";
String[] entetes = si.split(";");
Sheet globalStat = workbook.createSheet("statistiques gobales");
setXlsProperties(workbook);
int cellIndex = 0;
int rowIndex = 0;
Row row = globalStat.createRow(rowIndex++);
row = globalStat.createRow(rowIndex++);
row = globalStat.createRow(rowIndex++);
Map<String ,CellStyle> styles = makeCellStyles(workbook);
for (int i = 0; i < 9; i++) {
if (i != 4)
row.createCell(i).setCellValue("");
else {
row.createCell(i).setCellValue("Type Erreurs");
}
}
for (int i = 4; i < 8; i++) {
row.getCell(i).setCellStyle(styles.get("groupHeader"));
// row.getCell(i).getCellStyle().setBorderTop(CellStyle.BORDER_MEDIUM);
}
row.getCell(7).getCellStyle().setBorderRight(CellStyle.BORDER_MEDIUM);
// (groupHeaderStyle);
globalStat.addMergedRegion(new CellRangeAddress(2, 2, 4, 7));
// row.getCell(4).setCellStyle(groupHeaderStyle);
row = globalStat.createRow(rowIndex++);
cellIndex = 0;
for (String val : entetes) {
row.createCell(cellIndex++).setCellValue(val);
row.getCell(cellIndex - 1).setCellStyle(styles.get("rowHeader"));
}
int fileIndex = 0;
for (Integer[] info : lesstats) {
row = globalStat.createRow(rowIndex++);
cellIndex = 0;
row.createCell(cellIndex++).setCellValue(filescecked.get(fileIndex++));
row.getCell(0).setCellStyle(styles.get("rowHeader"));
for (Integer i : info) {
row.createCell(cellIndex).setCellValue(i);
row.getCell(cellIndex).setCellStyle(styles.get("data"));
cellIndex++;
}
}
System.out.println(lesstats.size());
for (int i = 1; i <= lesstats.get(0).length; i++) {
row.getCell(i).setCellStyle(styles.get("borderData"));
}
row = globalStat.createRow(rowIndex);
row.createCell(0);
for (int i = 1; i < 8; i++) {
row.createCell(i);
Integer limit = 3 + lesstats.size();
String col = "";
col += (char) (65 + i);
col += "3";
col += ":";
col += (char) (65 + i);
col += limit.toString() + ")";
System.out.println("\tSUM(" + col);
row.getCell(i).setCellFormula("SUM(" + col);
row.getCell(i).setCellStyle(styles.get("rowHeader"));
row.getCell(i).getCellStyle().setAlignment(CellStyle.ALIGN_CENTER);
row.getCell(i).getCellStyle().setDataFormat(format.getFormat("# ##0"));
}
for (int i = 0; i < 9; i++)
globalStat.autoSizeColumn(i);
//workbook.close();
workbook.write(fos);
fos.close();
workbook.close();
System.out.println(statfile + " is successfully written");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I've just discovered that if i remove the call to setCellFormula the issue disappears which doesnt make any sense.
I need help extracting all the file names within a folder in Business Objects. With the code I have now I can get the name of a single file within a folder. I want to get all the file names in that folder. The variable temp is where I enter the name of the file that I want. The variable doc is where the file name is retrieved, and the variable reportname is where I store doc to write to an external spreadsheet.
public class variable {
private static String expressionEx;
private static String nameEx;
private static String nameXE[] = new String[11];
private static String expressionXE[] = new String[11];
private static String query;
public static String reportName;
private static String reportPath;
/** This method writes data to new excel file * */
public static void writeDataToExcelFile(String fileName) {
String[][] excelData = preapreDataToWriteToExcel();// Creates first
// sheet in Excel
String[][] excelData1 = preapreDataToWriteToExcel1();// Creates
// second
// sheet in
// Excel
String[][] excelData2 = preapreDataToWriteToExcel2();// Creates third
// sheet in
// Excel
HSSFWorkbook myReports = new HSSFWorkbook();
HSSFSheet mySheet = myReports.createSheet("Variables");
HSSFSheet mySheet1 = myReports.createSheet("SQL Statement");
HSSFSheet mySheet2 = myReports.createSheet("File Info");
// edits first sheet
mySheet.setFitToPage(true);
mySheet.setHorizontallyCenter(true);
mySheet.setColumnWidth(0, 800 * 6);
mySheet.setColumnWidth(1, 7000 * 6);
// edits second sheet
mySheet1.setFitToPage(true);
mySheet1.setHorizontallyCenter(true);
mySheet1.setColumnWidth(0, 800 * 6);
mySheet1.setColumnWidth(1, 7000 * 6);
// edits third sheet
mySheet2.setFitToPage(true);
mySheet2.setHorizontallyCenter(true);
mySheet2.setColumnWidth(0, 800 * 6);
mySheet2.setColumnWidth(1, 2000 * 6);
HSSFRow myRow = null;
HSSFCell myCell = null;
// first sheet
for (int rowNum = 0; rowNum < excelData[0].length; rowNum++) {
myRow = mySheet.createRow(rowNum);
for (int cellNum = 0; cellNum < 4; cellNum++) {
myCell = myRow.createCell(cellNum);
myCell.setCellValue(excelData[rowNum][cellNum]);
}
}
try {
FileOutputStream out = new FileOutputStream(fileName);
myReports.write(out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
// second sheet
for (int rowNum = 0; rowNum < excelData1[0].length; rowNum++) {
myRow = mySheet1.createRow(rowNum);
for (int cellNum = 0; cellNum < 4; cellNum++) {
myCell = myRow.createCell(cellNum);
myCell.setCellValue(excelData1[rowNum][cellNum]);
}
}
try {
FileOutputStream out = new FileOutputStream(fileName);
myReports.write(out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
// third sheet
for (int rowNum = 0; rowNum < excelData2[0].length; rowNum++) {
myRow = mySheet2.createRow(rowNum);
for (int cellNum = 0; cellNum < 4; cellNum++) {
myCell = myRow.createCell(cellNum);
myCell.setCellValue(excelData2[rowNum][cellNum]);
}
}
try {
FileOutputStream out = new FileOutputStream(fileName);
myReports.write(out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* #param args
*/
public static String password;
public static String username;
public static String temp;
public variable() throws FileNotFoundException {
// TODO Auto-generated method stub
IEnterpriseSession oEnterpriseSession = null;
ReportEngines reportEngines = null;
try {
// String cmsname = "det0190bpmsdev3";
// String authenticationType = "secEnterprise";
String cmsname = "";
String authenticationType = "";
// Log in.
oEnterpriseSession = CrystalEnterprise.getSessionMgr().logon(
username, password, cmsname, authenticationType);
if (oEnterpriseSession == null) {
} else {
// Process Document
reportEngines = (ReportEngines) oEnterpriseSession
.getService("ReportEngines");
ReportEngine wiRepEngine = (ReportEngine) reportEngines
.getService(ReportEngines.ReportEngineType.WI_REPORT_ENGINE);
IInfoStore infoStore = (IInfoStore) oEnterpriseSession
.getService("InfoStore");
String query = "select SI_NAME, SI_ID from CI_INFOOBJECTS "
+ "where SI_KIND = 'Webi' and SI_INSTANCE=0 and SI_NAME ='"
+ temp + "'";
IInfoObjects infoObjects = (IInfoObjects) infoStore
.query(query);
for (Object object : infoObjects) {
IInfoObject infoObject = (IInfoObject) object;
String path = getInfoObjectPath(infoObject);
if (path.startsWith("/")) {
DocumentInstance widoc = wiRepEngine
.openDocument(infoObject.getID());
String doc = infoObject.getTitle();
reportPath = path;// this is the path of document
$$$$$$$$$ reportName = doc;// this is the document name
printDocumentVariables(widoc);
purgeQueries(widoc);
widoc.closeDocument();
}
}
// End processing
}
} catch (SDKException sdkEx) {
} finally {
if (reportEngines != null)
reportEngines.close();
if (oEnterpriseSession != null)
oEnterpriseSession.logoff();
}
}
public static void printDocumentVariables(DocumentInstance widoc) {
int i = 0;
// this is the report documents variables
ReportDictionary dic = widoc.getDictionary();
VariableExpression[] variables = dic.getVariables();
for (VariableExpression e : variables) {
nameEx = e.getFormulaLanguageID();
expressionEx = e.getFormula().getValue();
// stores variables in array
nameXE[i] = nameEx;
expressionXE[i] = expressionEx;
i++;
}
}
public static String getInfoObjectPath(IInfoObject infoObject)
throws SDKException {
String path = "";
while (infoObject.getParentID() != 0) {
infoObject = infoObject.getParent();
path = "/" + infoObject.getTitle() + path;
}
return path;
}
#SuppressWarnings("deprecation")
public static void purgeQueries(DocumentInstance widoc) {
DataProviders dps = widoc.getDataProviders();
for (int i = 0; i < dps.getCount(); ++i) {
DataProvider dp = (DataProvider) dps.getItem(i);
if (dp instanceof SQLDataProvider) {
SQLDataProvider sdp = (SQLDataProvider) dp;
sdp.purge(true);
query = sdp.getQuery().getSQL();
}
}
If Temp is going to hold the name of a unique folder, then you can use this code. Replace the String query = line with:
IInfoObjects oParents = infoStore.query("select si_id from ci_infoobjects where si_kind = 'folder' and si_name = '" + temp + "'");
if(oParents.size()==0)
return; // folder name not found
IInfoObject oParent = (IInfoObject)oParents.get(0);
String query = "select SI_NAME, SI_ID from CI_INFOOBJECTS "
+ "where SI_KIND = 'Webi' and si_parentid = " + oParent.getID();
I don't see in the code where you're populating the temp, username, or password variables, but I assume you just left that out of the listing intentionally. Obviously they will need to be defined.
Couple of other things I noticed in your code:
You are purging the query in each report, but not saving the report afterwards.
You are storing the report's SQL in an instance variable named query, but you also have a local variable named query in the variable constructor. This could very likely cause a conflict if you need the SQL value for something.
You have an "empty catch" for SDKException. SDKExceptions can happen for all kinds of reasons, and as it is you will not know why the program failed. You should at least be printing out the exception, or just let it bubble up.
I need to add a new sheet with different methods and headers within the same workbook. I'm able to add the new sheet but how do add the separate methods and headers for the second sheet? Right now both sheets are duplicate copies. Basically How would I add different data to both sheets. Any help would be appreciated and I always accept the answers and also up vote.
public class ExcelWriter {
Logger log = Logger.getLogger(ExcelWriter.class.getName());
private HSSFWorkbook excel;
public ExcelWriter() {
excel = new HSSFWorkbook();
}
public HSSFWorkbook getWorkbook() {
return excel;
}
public void writeExcelFile(String filename, String[] columns, Object[][] data, HSSFCellStyle[] styles,
HSSFCellStyle columnsStyle, String[] header, String[] footer) throws IOException {
FileOutputStream out = new FileOutputStream(filename);
HSSFSheet sheet = excel.createSheet("Daily Screening");
HSSFSheet sheet1 = excel.createSheet("Parcel Return");
int numHeaderRows = header.length;
createHeader(sheet,header,columns.length, 0);
createHeader(sheet1,header,columns.length, 0);
createColumnHeaderRow(sheet,columns,numHeaderRows,columnsStyle);
createColumnHeaderRow(sheet1,columns,numHeaderRows,columnsStyle);
int rowCtr = numHeaderRows;
for( int i = 0; i < data.length; i++) {
if (i > data.length -2)
++rowCtr;
else
rowCtr = rowCtr + 2;
createRow(sheet, data[i], rowCtr, styles);
}
int rowCtr1 = numHeaderRows;
for( int i = 0; i < data.length; i++) {
if (i > data.length -2)
++rowCtr1;
else
rowCtr1 = rowCtr1 + 2;
createRow(sheet1, data[i], rowCtr1, styles);
}
int totalRows = rowCtr1 + 1;
createHeader(sheet1,footer,columns.length, totalRows);
excel.write(out);
out.close();
}
private void createHeader(HSSFSheet sheet1, String[] header, int columns, int rowNum) {
for( int i = 0; i < header.length ; i++ ) {
HSSFRow row = sheet1.createRow(i + rowNum);
HSSFCell cell = row.createCell((short) 0);
String text = header[i];
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setCellValue(text);
HSSFCellStyle style = excel.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
HSSFFont arialBoldFont = excel.createFont();
arialBoldFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
arialBoldFont.setFontName("Arial");
style.setFont(arialBoldFont);
if (!isEmpty(header[i]) && rowNum < 1) {
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
}
cell.setCellStyle(style);
sheet1.addMergedRegion( new Region(i+rowNum,(short)0,i+rowNum,(short)(columns-1)) );
}
}
private HSSFRow createColumnHeaderRow(HSSFSheet sheet, Object[] values, int rowNum, HSSFCellStyle style) {
HSSFCellStyle[] styles = new HSSFCellStyle[values.length];
for( int i = 0; i < values.length; i++ ) {
styles[i] = style;
}
return createRow(sheet,values,rowNum,styles);
}
private HSSFRow createRow(HSSFSheet sheet1, Object[] values, int rowNum, HSSFCellStyle[] styles) {
HSSFRow row = sheet1.createRow(rowNum);
for( int i = 0; i < values.length; i++ ) {
HSSFCell cell = row.createCell((short) i);
cell.setCellStyle(styles[i]);
try{
Object o = values[i];
if( o instanceof String ) {
String text = String.valueOf(o);
cell.setCellValue(text);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
}
else if (o instanceof Double) {
Double d = (Double) o;
cell.setCellValue(d.doubleValue());
cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
}
else if (o instanceof Integer) {
Integer in = (Integer)o;
cell.setCellValue(in.intValue());
}
else if (o instanceof Long) {
Long l = (Long)o;
cell.setCellValue(l.longValue());
cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
}
else if( o != null ) {
String text = String.valueOf(o);
cell.setCellValue(text);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
}
}
catch(Exception e) {
log.error(e.getMessage());
}
}
return row;
}
public boolean isEmpty(String str) {
if(str.equals(null) || str.equals(""))
return true;
else
return false;
}
}
Report Generator Class
public class SummaryReportGenerator extends ReportGenerator {
Logger log = Logger.getLogger(SummaryReportGenerator.class.getName());
public SummaryReportGenerator(String reportDir, String filename) {
super( reportDir + filename + ".xls", reportDir + filename + ".pdf");
}
public String[] getColumnNames() {
String[] columnNames = {"ISC\nCode", "Total\nParcels", "Total\nParcel Hit\n Count",
"Filter Hit\n%", "Unanalyzed\nCount", "Unanalyzed\n%",
"Name\nMatch\nCount", "Name\nMatch\n%", "Pended\nCount",
"Pended\n%", "E 1 Sanction\nCountries\nCount", "E 1 Sanction\nCountries\n%", "Greater\nthat\n$2500\nCount", "Greater\nthat\n$2500\n%",
"YTD\nTotal Hit\nCount", "YTD\nLong Term\nPending", "YTD\nLong Term\n%"};
return columnNames;
}
public HSSFCellStyle getColumnsStyle(HSSFWorkbook wrkbk) {
HSSFCellStyle style = wrkbk.createCellStyle();
style.setWrapText(true);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
HSSFFont timesBoldFont = wrkbk.createFont();
timesBoldFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
timesBoldFont.setFontName("Times New Roman");
style.setFont(timesBoldFont);
return style;
}
public Object[][] getData(Map map) {
int rows = map.size();// + 1 + // 1 blank row 1; // 1 row for the grand total;
int cols = getColumnNames().length;
Object[][] data = new Object[rows][cols];
int row = 0;
for (int i=0; i < map.size(); i++ ){
try{
SummaryBean bean = (SummaryBean)map.get(new Integer(i));
data[row][0] = bean.getIscCode();
data[row][1] = new Long(bean.getTotalParcelCtr());
data[row][2] = new Integer(bean.getTotalFilterHitCtr());
data[row][3] = bean.getFilterHitPrctg();
data[row][4] = new Integer(bean.getPendedHitCtr());
data[row][5] = bean.getPendedHitPrctg();
data[row][6] = new Integer(bean.getTrueHitCtr());
data[row][7] = new Integer(bean.getRetiredHitCtr());
data[row][8] = new Integer(bean.getSanctCntryCtr());
data[row][9] = new Integer(bean.getC25Ctr());
data[row][10] = new Integer(bean.getCnmCtr());
data[row][11] = new Integer(bean.getCndCtr());
data[row][12] = new Integer(bean.getCnlCtr());
data[row][13] = new Integer(bean.getCneCtr());
data[row][14] = new Integer(bean.getVndCtr());
data[row][15] = new Integer(bean.getCilCtr());
data[row][16] = new Integer(bean.getHndCtr());
data[row][17] = new Integer(bean.getCnrCtr());
++row;
}
catch(Exception e) {
log.error(e.getMessage());
}
}
return data;
}
public String[] getHeader(String startDate, String endDate) {
Date today = new Date();
String reportDateFormat = Utils.formatDateTime(today, "MM/dd/yyyyHH.mm.ss");
String nowStr = Utils.now(reportDateFormat);
String[] header = {"","EXCS Daily Screening Summary Report ","",
"for transactions processed for the calendar date range",
"from " + startDate + " to " + endDate,
"Report created on " + nowStr.substring(0,10)+ " at "
+ nowStr.substring(10)};
return header;
}
public HSSFCellStyle[] getStyles(HSSFWorkbook wrkbk) {
int columnSize = getColumnNames().length;
HSSFCellStyle[] styles = new HSSFCellStyle[columnSize];
HSSFDataFormat format = wrkbk.createDataFormat();
for (int i=0; i < columnSize; i++){
styles[i] = wrkbk.createCellStyle();
if (i == 0){
styles[i].setAlignment(HSSFCellStyle.ALIGN_LEFT);
}else{
styles[i].setAlignment(HSSFCellStyle.ALIGN_RIGHT);
}
if (i == 1 || i == 2){
styles[i].setDataFormat(format.getFormat("#,###,##0"));
}
HSSFFont timesFont = wrkbk.createFont();
timesFont.setFontName("Times New Roman");
styles[i].setFont(timesFont);
}
return styles;
}
public String[] getFooter() {
String[] header = {"","Parcel Return Reason Code Reference","",
"DPM = Sender and/or recipient matches denied party",
"HND = Humanitarian exception not declared",
"CNM = Content not mailable under export laws",
"VND = Value of content not declared",
"CNR = Customer non-response",
"C25 = Content Value greater than $2500",
"CIL = Invalid license",
"C30 = More than one parcel in a calendar month",
"CNL = Content description not legible",
"CNE = Address on mailpiece not in English",
"RFN = Requires full sender and addressee names",
"DGS = Dangerous goods",
"R29 = RE-used 2976 or 2976A",
"ANE = PS Form 2976 or 2976A not in English",
"ICF = Incorrect Customs Declaration Form used",
"DPR = Declaration of purpose required",
"ITN = Internal Transaction Number (ITN), Export Exception/Exclusion Legend (ELL), or Proof of Filing Citation (PFC) is required",
"OTH = Other","",};
return header;
}
}
what you need is
HSSFSheet sheet = parentworkbookname.createSheet("Sample sheet2");