Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I went through some sample codes to export data to excel using Apache POI. However, I am not sure as to how we can export database query results to an excel file. I know that we must create cells in rows and then set values to the cell. But I already have the data in the resultset and must just export the same to an excel file. Can anyone provide me a small/easy code to do the same.
Thanks!
Try : Reference Apache POI's Developer Guide
Example Person table :
+------------------+
| NAME | ADDRESS |
+------------------+
| Jhone | USA |
| Smith | USA |
+------------------+
Example Program
Workbook wb = new HSSFWorkbook();
Sheet personSheet = wb.createSheet("PersonList");
Row headerRow = personSheet.createRow(0);
Cell nameHeaderCell = headerRow.createCell(0);
Cell addressHeaderCell = headerRow.createCell(1);
String sql = "select name, address from person_table";
PrepareStatement ps = connection.prepareStatement(sql);
ResultSet resultSet = ps.executeQuery();
int row = 1;
while(resultSet.next()) {
String name = resultSet.getString("name");
String address = resultSet.getString("address");
Row dataRow = personSheet.createRow(row);
Cell dataNameCell = dataRow.createCell(0);
dataNameCell.setCellValue(name);
Cell dataAddressCell = dataRow.createCell(1);
dataAddressCell.setCellValue(address);
row = row + 1;
}
String outputDirPath = "D:/PersonList.xls";
FileOutputStream fileOut = new FileOutputStream(outputDirPath);
wb.write(fileOut);
fileOut.close();
For HSSF format it is possible to use a Cocoon pipeline that delivers the results of a database query as XML to the POI serializer.
This has the advantage of not entangling the database query with the calling of the POI API.
I am investigating the amount of work required to upgrade the serializer to handle the XSSF format to overcome the 64k limit on the number of rows in the final speadsheet.
if youre using (or you can use) SqlResultSet then this solution fits you:
https://github.com/OfekRv/DraggerReports/blob/master/src/main/java/dragger/bl/exporter/ExcelReportExporter.java
public class ExcelReportExporter implements ReportExporter {
private static final char UNDER_LINE = '_';
private static final char SPACE = ' ';
private static final String SUFFIX = ".xlsx";
private static final int TITLE_ROW = 0;
private static final int HEADER_ROW = 3;
private static final int RESULTS_FIRST_ROW = HEADER_ROW + 1;
private static final int FIRST_COLUMN_INDEX = 0;
#Inject
QueryGenerator generator;
#Inject
QueryExecutor executor;
#Override
public File export(Report reportToExport) throws DraggerExportException {
String reportName = generateReportName(reportToExport);
SqlRowSet results = executor.executeQuery(generator.generate(reportToExport.getQuery()));
SqlRowSetMetaData resultsMetaData = results.getMetaData();
try (Workbook workbook = new XSSFWorkbook();) {
Sheet sheet = workbook.createSheet(reportName);
createTitle(reportToExport, workbook, sheet);
createHeaderRowFromMetadata(resultsMetaData, workbook, sheet);
int excelRowIndex = createDataTableFromResultset(results, resultsMetaData, workbook, sheet);
setTableAutoFilter(resultsMetaData, sheet, excelRowIndex);
saveExcelFile(reportName, workbook);
autoSizeColumns(resultsMetaData, sheet);
} catch (IOException e) {
throw new DraggerExportException("Could not create export file", e);
}
return new File(reportName);
}
private String generateReportName(Report reportToExport) {
return reportToExport.getName().replace(SPACE, UNDER_LINE) + UNDER_LINE + LocalDate.now() + SUFFIX;
}
private void autoSizeColumns(SqlRowSetMetaData resultsMetaData, Sheet sheet) {
for (int i = FIRST_COLUMN_INDEX; i < resultsMetaData.getColumnCount(); i++) {
sheet.autoSizeColumn(i);
}
}
private void saveExcelFile(String reportName, Workbook workbook) throws IOException, FileNotFoundException {
try (FileOutputStream fileOut = new FileOutputStream(reportName);) {
workbook.write(fileOut);
}
}
private void setTableAutoFilter(SqlRowSetMetaData resultsMetaData, Sheet sheet, int excelRowIndex) {
sheet.setAutoFilter(new CellRangeAddress(HEADER_ROW, excelRowIndex, FIRST_COLUMN_INDEX,
resultsMetaData.getColumnCount() - 1));
}
private int createDataTableFromResultset(SqlRowSet results, SqlRowSetMetaData resultsMetaData, Workbook workbook,
Sheet sheet) {
int excelRowIndex = RESULTS_FIRST_ROW;
CellStyle DataStyle = createDataCellStyle(workbook);
while (results.next()) {
Row row = sheet.createRow(excelRowIndex);
for (int i = FIRST_COLUMN_INDEX; i < resultsMetaData.getColumnCount(); i++) {
CreateCell(results.getObject(resultsMetaData.getColumnNames()[i]).toString(), DataStyle, row, i);
}
excelRowIndex++;
}
return excelRowIndex;
}
private void createHeaderRowFromMetadata(SqlRowSetMetaData resultsMetaData, Workbook workbook, Sheet sheet) {
Row headerRow = sheet.createRow(HEADER_ROW);
CellStyle headerStyle = createHeaderCellStyle(workbook);
for (int i = FIRST_COLUMN_INDEX; i < resultsMetaData.getColumnCount(); i++) {
CreateCell(resultsMetaData.getColumnNames()[i], headerStyle, headerRow, i);
}
}
private void CreateCell(String data, CellStyle DataStyle, Row row, int cellIndex) {
Cell cell = row.createCell(cellIndex);
cell.setCellValue(data);
cell.setCellStyle(DataStyle);
}
}
Related
I have property file with column name and values. How to read the file with two rows simultaneously and add Key Value pair in the has-map.
Also if any Key Name get's no mapping then that should be omitted from the map.
public class ExcelReader {
public static ArrayList<String> ar = new ArrayList<String>();
public static ArrayList<Integer> val = new ArrayList<Integer>();
public static LinkedHashMap<String, Integer> cmMappingHashMap = new
LinkedHashMap<String, Integer>();
public static String str;
public static Row row;
public static void main(String[] args)throws IOException{
String excelFilePath = "C:\\Users\\test\\Downloads\\contacts.xlsx";
FileInputStream inputStream = new FileInputStream(new File(excelFilePath));
Workbook workbook = new XSSFWorkbook(inputStream);
Sheet firstSheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = firstSheet.rowIterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Row row2 = rowIterator.next();
row2.setRowNum(1);
System.out.println(row.getRowNum());
// Now let's iterate over the columns of the current row
Iterator<Cell> cellIterator = row.cellIterator();
Iterator<Cell> cellIterator1 = row2.cellIterator();
while (cellIterator.hasNext()&&cellIterator1.hasNext()) {
Cell cell = cellIterator.next();
Cell cell1 = cellIterator1.next();
System.out.println(cell.getColumnIndex());
System.out.print(cell.getStringCellValue()+ "--"+cell1.getNumericCellValue());
}
}
}
}
With the above code getting exception in thread "main" java.util.NoSuchElementException
I wanted to add the First Row's Cell 1 to second rows cell 1 like wise follows
Key ----Value
Name----1
ID------2
Name----3
I have created following code to achieve above based on various inputs present on the stack.
public void readPosition() throws FileNotFoundException, IOException {
columnNameArray = new String[propertyFilecolumnCount];
Workbook wb = null;
wb = new XSSFWorkbook(new FileInputStream(new
File("C:\\Users\\aaa\\Downloads\\Mapping_Data_Upload.xlsx")));
Sheet sheet = wb.getSheetAt(0);
Iterator<Row> itr = sheet.iterator();
while(itr.hasNext()){
Row row = itr.next();
Iterator<Cell> cellItrator = row.iterator();
if(row.getRowNum()==0){
while(cellItrator.hasNext()){
Cell cell = cellItrator.next();
String cellString =cell.toString();
if(cellString.length()!=0){
columnNameArray[cell.getColumnIndex()]=cellString;
}
}
}
if(row.getRowNum()==1){
columnValueArray=new String[columnNameArray.length];
int columnIndex=0;
List<Cell> cells = new ArrayList<Cell>();
int lastColumn = Math.max(row.getLastCellNum(), 7);
for (int cn = 0; cn < lastColumn; cn++) {
Cell c = row.getCell(cn, Row.RETURN_BLANK_AS_NULL);
if(c==null){
cellValue="Null";
columnIndex =columnIndex+1;
columnValueArray[columnIndex]=cellValue;
}
else{
cells.add(c);
columnValueArray[c.getColumnIndex()]=c.toString();
columnIndex=c.getColumnIndex();
}
}
for (int j=0,int k=0;j<columnNameArray.length && k<columnValueArray.length;j++,k++){
if(columnValueArray[k].equalsIgnoreCase("Null")){
}
else{
double val=Double.parseDouble(columnValueArray[k]);
int value=(int) Math.round(val);
MappingHashMap.put(columnNameArray[j], value);
}
}
columnNameArray=null;
columnValueArray=null;
}
Because for some columns I am not getting mapping because that is not present in the data file. So I have to remove that columnName from the has map.
ID | FName | LName | Address| City| Zip| Degree| Stdt| EndDt|
1 | 2 | 3 |4 | 5 | | | 6 | 7 |
This way I am getting out put as follows by using above code. Is there any effective way to get the following
Key ----Value
ID---1
FName----2
LName----3
Address---4
City------4
Stdt----5
enddt----6
Instead of reading the two lines directly, you can create a model class with attributes Name, ID and then you can instantiate the object and assign the values.
Hope this helps!
Please before you down vote this, I was not able to find an example of reading a web table and writing it to an Excel file. If you happen to find that link kindly provide it. I have found plenty of examples on how to write to an Excel file but without reading from web table part.
Here is my code:
public class WebTable1 {
public static void main(String[] args) throws IOException {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.w3schools.com/html/html_tables.asp");
//tr means Row, this table has 7 rows including Header
///td means Column, this table has 3 columns
//*[#id="customers"]/tbody/tr[2]/td[1]
//*[#id="customers"]/tbody/tr[7]/td[1]
//Notice above the pattern, only the values are changing for tr[??]- which is why we will break it down into 2 String
//below and then concatinate them as String
String beforeXpath_Company = "//*[#id='customers']/tbody/tr["; // changed customer to single quote
String aferXpath_Company = "]/td[1]"; //Company is column 1
String beforeXpath_Contact = "//*[#id='customers']/tbody/tr[";
String aferXpath_Contact = "]/td[2]"; // Contact is column 2
String beforeXpath_Country = "//*[#id='customers']/tbody/tr[";
String aferXpath_Country = "]/td[3]"; // Country is column 3
//Find number of rows so that we do not use hard coded values
List<WebElement> totalRows = driver.findElements(By.xpath("//table[#id='customers']//tr"));
int rows=totalRows.size();
for (int i = 2; i <rows; i++) { //we start from 2 because 1 is column name
String actualXpath = beforeXpath_Company + i + aferXpath_Company;
String companyName = driver.findElement(By.xpath(actualXpath)).getText();
System.out.println(companyName);
String actualXpath_Contact = beforeXpath_Contact + i + aferXpath_Contact;
String contactName = driver.findElement(By.xpath(actualXpath_Contact)).getText();
System.out.println(contactName);
String actualXpath_Country = beforeXpath_Country + i + aferXpath_Country;
String countryName = driver.findElement(By.xpath(actualXpath_Country)).getText();
System.out.println(countryName);
//Try to following to write to an Excel file in C drive
Workbook wb = new HSSFWorkbook();
CreationHelper createHelper = wb.getCreationHelper();
Sheet sheet1 = wb.createSheet("Sheet1");
Row row = sheet1.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue(createHelper.createRichTextString(companyName));
FileOutputStream fileOut = new FileOutputStream("C:\\MyTemp\\Test.xls");
wb.write(fileOut);
fileOut.close();
}
}
}
Thanks in advance.
Taking your existing table extraction code, you can do something like this:
public class WebTable1 {
public static void main(String[] args) throws IOException {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.w3schools.com/html/html_tables.asp");
String beforeXpath_Company = "//*[#id='customers']/tbody/tr["; // changed customer to single quote
String aferXpath_Company = "]/td[1]"; //Company is column 1
String beforeXpath_Contact = "//*[#id='customers']/tbody/tr[";
String aferXpath_Contact = "]/td[2]"; // Contact is column 2
String beforeXpath_Country = "//*[#id='customers']/tbody/tr[";
String aferXpath_Country = "]/td[3]"; // Country is column 3
//Find number of rows so that we do not use hard coded values
List<WebElement> totalRows = driver.findElements(By.xpath("//table[#id='customers']//tr"));
int rows=totalRows.size();
// Create a workbook and a sheet in it
Workbook wb = new HSSFWorkbook();
Sheet sheet1 = wb.createSheet("Sheet1");
// Create a table header
Row row = sheet.createRow(0);
row.createCell(0).setCellValue("Company name");
row.createCell(1).setCellValue("Contact name");
row.createCell(2).setCellValue("Country");
for (int i = 2; i <rows; i++) { //we start from 2 because 1 is column name
String actualXpath = beforeXpath_Company + i + aferXpath_Company;
String companyName = driver.findElement(By.xpath(actualXpath)).getText();
String actualXpath_Contact = beforeXpath_Contact + i + aferXpath_Contact;
String contactName = driver.findElement(By.xpath(actualXpath_Contact)).getText();
String actualXpath_Country = beforeXpath_Country + i + aferXpath_Country;
String countryName = driver.findElement(By.xpath(actualXpath_Country)).getText();
Row row = sheet1.createRow(i - 1);
row.createCell(0).setCellValue(companyName);
row.createCell(1).setCellValue(contactName);
row.createCell(2).setCellValue(countryName);
}
FileOutputStream fileOut = new FileOutputStream("C:\\MyTemp\\Test.xls");
wb.write(fileOut);
fileOut.close();
}
}
I am using JAVA 8 and Apache POI 3.17. I have an Excel file and i want to keep only few lines and delete the others. But my Excel have 40K rows and deleting them one by one is quite long (nearly 30 min :/ )
So i try to change my way of doing it. Now i think it's better to only take rows that i need in the excel source and copy to another new one. But what i have tried so far is not efficient.
I have all my rows and want to keep in a List. But this not working and create me a blank excel :
public void createExcelFileFromLog (Path logRejetFilePath, Path fichierInterdits) throws IOException {
Map<Integer, Integer> mapLigneColonne = getRowAndColumnInError(logRejetFilePath);
Workbook sourceWorkbook = WorkbookFactory.create(new File(fichierInterdits.toAbsolutePath().toString()));
Sheet sourceSheet = sourceWorkbook.getSheetAt(0);
List<Row> listLignes = new ArrayList<Row>();
// get Rows from source Excel
for (Map.Entry<Integer, Integer> entry : mapLigneColonne.entrySet()) {
listLignes.add(sourceSheet.getRow(entry.getKey()-1));
}
// The new Excel
Workbook workbookToWrite = new XSSFWorkbook();
Sheet sheetToWrite = workbookToWrite.createSheet("Interdits en erreur");
// Copy Rows
Integer i = 0;
for (Row row : listLignes) {
copyRow(sheetToWrite, row, i);
i++;
}
FileOutputStream fos = new FileOutputStream(config.getDossierTemporaire() + "Interdits_en_erreur.xlsx");
workbookToWrite.write(fos);
workbookToWrite.close();
sourceWorkbook.close();
}
private static void copyRow(Sheet newSheet, Row sourceRow, int newRowNum) {
Row newRow = newSheet.createRow(newRowNum);
newRow = sourceRow;
}
EDIT : Change the method of copyRow it's better but the date have weird format and blank cells from the original row are gone.
private static void copyRow(Sheet newSheet, Row sourceRow, int newRowNum) {
Row newRow = newSheet.createRow(newRowNum);
Integer i = 0;
for (Cell cell : sourceRow) {
if(cell.getCellTypeEnum() == CellType.NUMERIC) {
newRow.createCell(i).setCellValue(cell.getDateCellValue());
} else {
newRow.createCell(i).setCellValue(cell.getStringCellValue());
}
i++;
}
}
EDIT 2 : To keep blank cell
private static void copyRow(Sheet newSheet, Row sourceRow, Integer newRowNum, Integer cellToColor) {
Row newRow = newSheet.createRow(newRowNum);
//Integer i = 0;
int lastColumn = Math.max(sourceRow.getLastCellNum(), 0);
for(int i = 0; i < lastColumn; i++) {
Cell oldCell = sourceRow.getCell(i, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
if(oldCell == null) {
newRow.createCell(i).setCellValue("");
} else if (oldCell.getCellTypeEnum() == CellType.NUMERIC) {
newRow.createCell(i).setCellValue(oldCell.getDateCellValue());
} else {
newRow.createCell(i).setCellValue(oldCell.getStringCellValue());
}
}
}
I want to create an excel document with 5 sheets, the data for the sheets is dynamic and I have a maximum row limit.
currently my approach is creating one sheet at a time, and filling it with data. I am checking if max rows have been exceeded, and creating a new excel document.
However this will not wait to check if the other sheets are also exceeding the max row limit before creating the new workbook
My code samples
private void populateDetailsSheets(String[] data) throws IOException
{
currentRow = getCurrentRow();
rowCount++;
short cellNumber = 0;
for (String value : data)
{
POIExcelUtil.createCellWithContent(currentRow,value,cellNumber++).setCellStyle(contentStyle);
}
writeToFileOnExhaustingMaxRows();
}
private void writeToFileOnExhaustingMaxRows() throws IOException
{
if(sheet.getLastRowNum() + 2 > Integer.valueOf(SystemProperty.MAX_RECORDS_PER_EXCEL))
{
writeToFile();
rowCount = 0;
createWorkbook();
titleStyle = createTitleStyle();
headerStyle = createHeaderStyle();
columnHeaderStyle = createColumnHeaderStyle();
columnHeaderStyle.setBorderLeft(CellStyle.BORDER_MEDIUM);
columnHeaderStyle.setBorderTop(CellStyle.BORDER_MEDIUM);
columnHeaderStyle.setBorderRight(CellStyle.BORDER_MEDIUM);
columnHeaderStyle.setBorderBottom(CellStyle.BORDER_MEDIUM);
contentStyle = createCellStyle();
contentStyle.setBorderLeft(CellStyle.BORDER_THIN);
contentStyle.setBorderTop(CellStyle.BORDER_THIN);
contentStyle.setBorderRight(CellStyle.BORDER_THIN);
contentStyle.setBorderBottom(CellStyle.BORDER_THIN);
rowCount = 0;
createSheet("title sheet");
populateReportSettingsSheet();
rowCount =0;
createSheet(sheetNames[index]);
setColumnWidth();
createColumnHeader();
}
}
I am assuming that you want to jump to next sheet when the sheet one is full. Here the trick.
public class JumpToNewSheet {
private static HSSFSheet allocateNewSheet(HSSFWorkbook wb, String sheetName) {
HSSFSheet sheet = wb.createSheet(sheetName);
/*You can add style here too or write header here*/
return sheet;
}
public HSSFWorkbook exportExcel_xls(MyTable table) {
int cellNumber = 12;
List<TupleData> tuples = table.getTuples();
HSSFWorkbook wb = new HSSFWorkbook();//Whole book
HSSFSheet currentSheet = allocateNewSheet(wb, "SHEET");//Initial sheet
int sheetCounter = 1;//Start at 1 because we already created Initial sheet
int rowCounter = 0;//1st row in sheet
for(TupleData t: tuples) {//Loop through data
if(rowCounter % 65535 == 0) {//Max row reached, build new sheet
//Increase sheetCounter
sheetCounter++;
String new_sheetName = "SHEET_"+sheetCounter;//Name of sheet
currentSheet = allocateNewSheet(wb, new_sheetName);//Point currentSheet to new sheet
//Reset rowCounter to 0
rowCounter = 0;
}
Row row = currentSheet.createRow(rowCounter);
for(int i=0; i <=cellNumber; i++) {
Cell cell = row.createCell(i);
//Write data.......
//.............
}//End inner for loop
rowCounter++;
}//End for loop
}//End exportExcel_xls(MyTable table)
}
I am using APACHE POI 3.0 to add sheets to existing excel sheet. It works fine.
But as APACHE POI has limitations about making charts, I used a template excel file to create charts, which also worked fine, but this always result in new excel file.
If I have an existing excel sheet and I want to add a sheet, having charts, I am not able to do it. As, when I create charts, I use template file and it always makes a new excel file.
so I was wondering if there is any solution of it of adding sheets to excel, where the sheets have charts
public class TagBrowserSelection
{
private static String[] excelBarPlot_Template = { "","barPlot_1Panel_template.xlsx"};
private static String[] excelPieChart_Template = { "","pieChart_1Panel_template.xlsx"};
private static String[] excelPieAndBarPlot_Template = { "","pieAndBarChart_1Panel_template.xlsx"};
private static String REGEX = "";
static public boolean makeTagBrowserSelection(String strOutputFileName, ArrayList<TagBrowserChildPanel> childList, String sheetName, boolean addSheet, ArrayList<Boolean> chartAttributes)
{
// chart attributes
boolean addBarChart = chartAttributes.get(0);
boolean addPieChart = chartAttributes.get(1);
boolean addNoTag = chartAttributes.get(2);
boolean addZeros = chartAttributes.get(3);
REGEX = "^" + sheetName;
Pattern p = Pattern.compile(REGEX);
String[] templateArray = null;
if (addBarChart && addPieChart)
templateArray = excelPieAndBarPlot_Template;
else if (addBarChart)
templateArray = excelBarPlot_Template;
else if (addPieChart)
templateArray = excelPieChart_Template;
try
{
int number = childList.size();
XSSFWorkbook workbook = null;
XSSFWorkbook wb = null;
XSSFSheet sheet = null;
int col_num = 0;
int row_num = 0;
XSSFRow row = null;
XSSFCell cell = null;
// if adding sheet to existing excel file
if (addSheet)
{
FileInputStream fis = new FileInputStream(new File(strOutputFileName));
workbook = new XSSFWorkbook(fis);
fis.close();
// number of existing sheets in excel file
int numberOfSheets = workbook.getNumberOfSheets();
// check is sheetName exists already
if (isSheetExist(sheetName, workbook))
{
int counter = 1;
for (int ii = 0; ii < numberOfSheets; ii++)
{
Matcher m = p.matcher(workbook.getSheetName(ii));
if (m.find())
counter++;
}
sheetName = sheetName + " (" + counter + ")";
}
}
else
{
workbook = new XSSFWorkbook();
}
======================================================================
// if template file needs to be used(if bar chart/pie chart option is selected)
if (templateArray != null)
{
InputStream is = TagBrowserSelection.class.getClassLoader().getResourceAsStream(templateArray[number]);
wb = new XSSFWorkbook(OPCPackage.open(is));
sheet = wb.getSheetAt(0);
// wb.close();
}
else
{
sheet = workbook.createSheet(sheetName);
}
// Freeze top two row
// sheet.createFreezePane(0, 1, 0, 1);
// Filling up the workbook and performing the row/column formatting
for (TagBrowserChildPanel child : childList)
{
// Check if row is already created before(previous tag category)
row = sheet.getRow(0);
if (row == null)
row = sheet.createRow(0);
// Adding tag category name as header
String tagCategory = child.getSelectedCategory().getName();
cell = row.createCell(col_num);
cell.setCellValue(tagCategory);
row = sheet.getRow(1);
if (row == null)
row = sheet.createRow(1);
// Adding column headers
cell = row.createCell(col_num);
cell.setCellValue("tag");
cell = row.createCell(col_num + 1);
cell.setCellValue("counts");
row_num = 2;
// Adding tag category document summary(name and counts)
ArrayList<TagSummaryItem> tagSummary = child.getTagChartCounts();
for (int i = 0; i < tagSummary.size(); i++)
{
// Check if row is already created before(previous tag category)
row = sheet.getRow(row_num);
if (row == null)
row = sheet.createRow(row_num);
cell = row.createCell(col_num);
if (!addNoTag)
{
if (tagSummary.get(i).m_strTag == "[No Tag]")
continue;
}
if (!addZeros)
{
if (tagSummary.get(i).m_nCount == 0)
continue;
}
cell.setCellValue(tagSummary.get(i).m_strTag);
cell = row.createCell(col_num + 1);
cell.setCellValue(tagSummary.get(i).m_nCount);
row_num++;
}
// auto-size of tag column
sheet.autoSizeColumn(col_num);
col_num = col_num + 3;
}
FileOutputStream out = new FileOutputStream(strOutputFileName);
if (templateArray != null)
{
wb.setSheetName(0, sheetName);
wb.write(out);
wb.close();
}
else
{
workbook.write(out);
workbook.close();
}
out.close();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
Above is my code, its one code. I split into two sections. Section is the one which uses template to make chart excel sheet.
there's the method cloneSheet() in the HSSFWorkbook class. Try it.