Skip to content

Instantly share code, notes, and snippets.

@amitasehrawat
Created September 10, 2019 05:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amitasehrawat/789a073b25cd99c05002a37c68c53cfd to your computer and use it in GitHub Desktop.
Save amitasehrawat/789a073b25cd99c05002a37c68c53cfd to your computer and use it in GitHub Desktop.
java_CreateExcel
import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class excel_Functions1 {
public static void main(String[] args)
{
String SheetName = "MySheet";
try
{
XSSFWorkbook myWorkBook = new XSSFWorkbook();
XSSFSheet mySheet = myWorkBook.createSheet(SheetName);
// Create XSSFRow and XSSFCell
XSSFRow myRow = null;
XSSFCell myCell = null;
String excelData[] = new String[3];
excelData[0] = "First Name";
excelData[1] = "Last Name";
excelData[2] = "Country";
for(int i=0;i<1;i++) //This runs once to create 1 row
{
myRow = mySheet.createRow(i);
for(int j=0;j<3;j++) //This runs thrice to create and set column values to 'excelData"
{
myCell = myRow.createCell(j);
myCell.setCellValue(excelData[j]);
}
}
String directoryName = "temp";
File file = new File(directoryName);
if (!file.exists())
{
if (file.mkdir())
{
System.out.println("Directory is created!");
}
else
{
System.out.println("Failed to create directory!");
}
}
else
{
System.out.println("Directory already exists!");
}
String fileSeparator = System.getProperty("file.separator");
String relativePath = directoryName+fileSeparator+"MyExcelFile.xlsx";
System.out.println("relativePath:"+relativePath);
file = new File(relativePath);
FileOutputStream out = new FileOutputStream(file);
myWorkBook.write(out);
myWorkBook.close();
out.close();
String filePath = file.getAbsolutePath();
System.out.println("Excel File created:"+filePath);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment