Overwriting a file that is currently being used - excel

I want to create a new sheet on an Excel workbook that is currently open/being used. In my program, I ask the user for a new worksheet name, but when I have the Excel file open, it returns me a FileNotFoundException because it "cannot access the file because it is being used by another process." Is it possible to fix this? Or should I ask the user to close the file first?
public void exportToExcel() {
String excelFileName = null; // the name/directory/address of the excel file created/selected
FileInputStream excelFileIn = null; // allows us to connect to the Excel file so we can read it
FileOutputStream excelFileOut = null; // allows us to connect to the Excel file so we can write to it
ExcelFileUtility eUtil = new ExcelFileUtility(); // used open an excel file
if(columnsQuery != null) {
try {
excelFileName = eUtil.getFile(FileExtensions.XLS);
if(excelFileName != null) {
excelFileIn = new FileInputStream(new File(excelFileName));
workbook = new HSSFWorkbook(excelFileIn);
exportColsToWorkbook(columnsQuery);
excelFileOut = new FileOutputStream(excelFileName);
workbook.write(excelFileOut);
// close everything
workbook.close();
excelFileIn.close();
excelFileOut.close();
}
}
catch (IOException e) {
e.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
}
}
}

Related

FileInputStream issue - App has stopped working

I am having trouble with FileInputStream in Android Studio. My application has stopped working when I use it to read file .txt in the internal memory (I have writen data to this file successfully). I have try many solutions but they didn't work. Can anyone give the solution for this problem? Here is my code. Thanks very much. (I have added users-permission "WRITE_EXTERNAL_STORAGE" and "READ_EXTERNAL_STORAGE").
String fileName = "infoProfile.txt";
private int readData() {
try {
String path = MainActivity.this.getFilesDir().getAbsolutePath() + "/" + fileName;
FileInputStream in = openFileInput(path);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
ArrayList<String> str = new ArrayList<>();
String data = "";
while ((data = reader.readLine()) != null) {
str.add(data);
}
in.close();
if (str.isEmpty())
return 0;
etName.setText(str.get(0));
etEmail.setText(str.get(1));
etPhone.setText(str.get(2));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return 1;
}

How to create file in java

File Name = new File("G:/Java/lesson25_1/Name.txt");
if(Name==null){
JOptionPane.showMessageDialog(this, "Details are missing");
}
try{
FileReader fr1 = new FileReader("Name.txt");
BufferedReader br1=new BufferedReader(fr1);
String str=br1.readLine();
br1.close();
when i do this in a method it dosn't work when i click the button
There is a method for file called exists to check if the given file exist or not.
String path = "G:/Java/lesson25_1/Name.txt";
File file = new File(path);
if(!file.isFile() || !file.canRead()){
JOptionPane.showMessageDialog(this, "Details are missing");
} else {
try {
FileReader fr1 = new FileReader("Name.txt");
BufferedReader br1=new BufferedReader(fr1);
String str=br1.readLine();
br1.close();
} catch (Exception e){
e.printStackTrace();
}
}

issue in text to excel file convert

i m creating excel file from text file using Microsoft.Office.Interop.Excel;
here is my code
private void button1_Click(object sender, EventArgs e)
{
// Reading the text file - StreamReader include System.IO namespace
StreamReader objReader = new StreamReader(#"C:\Users\pci218\Desktop\TextToExcelFormApplication\TextToExcelFormApplication\Text\pop3.txt");// Please give the file path
string sLine = "";
ArrayList arrText = new ArrayList();// Include System.Collections.Generic namespace
while (sLine != null)
{
sLine = objReader.ReadLine();
if (sLine != null)
arrText.Add(sLine);
}
callExcel(arrText, true);
}
private void callExcel(ArrayList arrText, bool value)
{
try
{
// Change Your String here
String textString = null;
foreach (var item in arrText)
{
textString = textString + item + Environment.NewLine;
}
Clipboard.SetText(textString);
Microsoft.Office.Interop.Excel.Application xlexcel;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlexcel = new Excel.Application();
// for excel visibility
//xlexcel.Visible = true;
// Creating a new workbook
xlWorkBook = xlexcel.Workbooks.Add(misValue);
// Putting Sheet 1 as the sheet you want to put the data within
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
// creating the range
Excel.Range CR = (Excel.Range)xlWorkSheet.Cells[1, 1];
CR.Select();
xlWorkSheet.Paste(CR, false);
if (value == true)
{
try
{
// saving the file as .xls
xlWorkSheet.SaveAs(#"C:\Users\U0153056\Desktop\receivedNew.xls");
}
catch (Exception)
{
MessageBox.Show("File already exist");
}
}
else
{
try
{
// saving the file as .xlsx
xlWorkSheet.SaveAs(#"C:\Users\U0153056\Desktop\receivedNew.xlsx");
}
catch (Exception)
{
MessageBox.Show("File already exist");
}
}
xlexcel.Quit();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
but i m getting "Retrieving the COM class factory for component with CLSID"
error. i dont have microsoft office installed in my PC.is tht the problem? due to that m getting this error? anyone have idea .pls help.
Unfortunately, you can't use Microsoft.Office.Interop.Excel without having Microsoft Office Excel 2007 or later version installed.
... you must have Microsoft Office Excel 2007 and Microsoft Office
Word 2007, or later versions, installed on your computer.
Check this link for more information.

Apache poi autosizecolumn is not working

i want to write a list of object to an excel file.But autoSizeColumn is not working.My code is below :
List<ReportTmPerHour> reportTm = reportTm();
Iterator<ReportTmPerHour> iterator = reportTm.iterator();
String fileName="C:\\Users\\kkk\\Desktop\\mmm_ccc.xlsx";
Workbook workbook = null;
if(fileName.endsWith("xlsx")){
workbook = new XSSFWorkbook();
}else if(fileName.endsWith("xls")){
workbook = new HSSFWorkbook();
}else{
try {
throw new Exception("invalid file name, should be xls or xlsx");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Sheet sheet = workbook.createSheet("TM");
int rowIndex = 0;
createHeadersForTm(sheet);
while(iterator.hasNext()){
ReportTmPerHour reportTmPerHour = iterator.next();
Row row = sheet.createRow(++rowIndex);
Cell cell = row.createCell(0);
cell.setCellValue(reportTmPerHour.getIsemriNo());
cell.setCellStyle(arg0);
Cell cell10 = row.createCell(1);
cell10.setCellValue(reportTmPerHour.getSube());
Cell cell11=row.createCell(2);
cell11.setCellValue(reportTmPerHour.getAob());
Cell cell12=row.createCell(3);
cell12.setCellValue(reportTmPerHour.getKesintiBildirim());
Cell cell13=row.createCell(4);
cell13.setCellValue(reportTmPerHour.getAciklama());
Cell cell14=row.createCell(5);
cell14.setCellValue(reportTmPerHour.getEtkilenenMahalleler());
Cell cell15=row.createCell(6);
if (reportTmPerHour.getBaslamaZamani()!=null) {
cell15.setCellValue(reportTmPerHour.getBaslamaZamani());
}
Cell cell16=row.createCell(7);
cell16.setCellValue(reportTmPerHour.getTahminiBitisZamani());
Cell cell17=row.createCell(8);
cell17.setCellValue(reportTmPerHour.getTmName());
Cell cell18=row.createCell(9);
cell18.setCellValue(reportTmPerHour.getEtkilenensayi());
}
columnAutoSize(sheet);
//lets write the excel data to file now
FileOutputStream fos;
try {
fos = new FileOutputStream(new File(fileName));
workbook.write(fos);
fos.close();
System.out.println(fileName + " written successfully");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
It does not adjust the columns according to the biggest column size.I use the last version of poiI have seen lots of questions like this.I adjust the size of columns after filling the cells.But this is not working also.Thanx in advance
EDIT
My columnAutoSize(sheet) is below :
private void columnAutoSize(Sheet sheet) {
for(int columnPosition = 1; columnPosition< 9; columnPosition++) {
sheet.autoSizeColumn(columnPosition);
}
}

org.apache.poi.openxml4j.exceptions.InvalidOperationException: Can't open the specified file

My code is not working, it always shows the above mentioned exception.
but I can always see the tmp file being generated.
here is the code, can someone please suggest something:
FileInputStream fis =null;
try{
fis= new FileInputStream(new File("/home/amar/Desktop/new/abc.xls"));
Workbook wb = new org.apache.poi.xssf.usermodel.XSSFWorkbook(fis);
int numOfSheets = wb.getNumberOfSheets();
System.out.println("bhargo num of sheets is " + numOfSheets);
for(int i=0; i<numOfSheets; i++){
org.apache.poi.ss.usermodel.Sheet sheet = wb.getSheetAt(i);
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext())
{
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = (Cell) cellIterator.next();
if (cell.getCellType() == cell.CELL_TYPE_STRING) {
System.out.println("bhargo cell value is " + cell.getStringCellValue().trim());
}
}
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
System.out.println("bhargo, closing the stream");
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
There are a number of issues here:
fis= new FileInputStream(new File("/home/amar/Desktop/new/abc.xls"));
Workbook wb = new org.apache.poi.xssf.usermodel.XSSFWorkbook(fis);
Firstly, as explained in the Apache POI documentation, don't use an InputStream if you have a file! It's slower and uses more memory
Secondly, XSSF is the code for working with .xlsx files, but your file is a .xls one, so that won't work.
Thirdly, Apache POI has code which will automatically work out what kind of file yours is, and create the appropriate workbook for you
Your code should therefore instead be
Workbook wb = WorkbookFactory.create(new File("/home/amar/Desktop/new/abc.xls"));
This will create the right kind of workbook, direct from the file
I was able to solve my problem.
I am working on linux so it was saving the file in the older version of excel

Resources