Java io ioexception invalid header signature

Как разрешить неверную подпись заголовка; прочитать 0x6576206C6D783F3C, ожидаемая ошибка 0xE11AB1A1E011CFD0 java?

Я экспортирую файл из веб-приложения в формате .xls. Когда я пытаюсь прочитать этот файл, он выдает ошибку:

java.io.IOException: Invalid header signature; read 0x6576206C6D783F3C, expected 0xE11AB1A1E011CFD0

Это экспортированный файл, поэтому изменить его формат невозможно.

Вот мой код и прикрепленный файл Excel:

public void verifyExportedData() throws Exception < String filename = "Top_Down_Planning_by_Investment.xls" File=new FileInputStream(new File("testdata/"+filename)); HSSFWorkbook workbook = new HSSFWorkbook(File); HSSFSheet sheet=workbook.getSheet("Top Down Planning by Investmen"); DataFormatter formatter = new DataFormatter(); System.out.println("Cell data : "+sheet.getRow(0).getCell(1)); >

Приходилось ли вам сталкиваться с требованиями, в которых вас могли попросить поднять тревогу или выдать ошибку, когда метод Java занимает больше.

Управление транзакциями JDBC — это мощная функция, которая позволяет рассматривать группу операций с базой данных как единую единицу работы. Оно.

WebClient — это реактивный веб-клиент, представленный в Spring 5. Это реактивное, неблокирующее решение, работающее по протоколу HTTP/1.1.

Ответы 1

«Ожидаемые» и «фактические» подписи файлов выводятся в порядке, обратном нормальному. (Это, вероятно, обратный порядок байтов по сравнению с прямым порядком байтов . )

Согласно источнику, который я нашел в Интернете, подпись файла «.xls»

что соответствует «ожидаемой» подписи (перевернутая). Поэтому, если я переверну «настоящую» подпись, я получу

Если я конвертирую этот шестнадцатеричный код в ASCII, я получаю

Вам это знакомо? Вот типичный заголовок XML-файла:

Похоже, вы экспортировали файл в формате на основе XML, а не в устаревшем формате «.xls». Я предполагаю, что файл имеет формат «.xlxs» или аналогичный.

Я думаю, что вам нужно использовать XSSF, а не HSSH:

Спасибо за объяснение @Stephen C! Я экспортирую файл в формате .xls, который преобразуется из формата на основе XML из приложения. В приложении есть ссылка «Экспорт в Excel», которая предоставляет этот файл Excel. Любая идея, как я могу его успешно прочитать или сделать формат заголовка .xls ??

Источник

Invalid Header Signature

Solution 2: try to open the file in microsoft office Excel then a pop message will appear to inform you that that file you are trying to open isn’t an excel file, and give you the choice to open it any way, so just open it and save it as excel file. Excel will happily load html files (rendering the table as the spreadsheet) and csv files, and doesn’t warn you that you’ve got the wrong extension on them.

Invalid Header Signature

Here I want to extract the data from .xlsx file and for that I already add the poi jar and created the reference of fileInputStream

package demo; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; public class DemoExcel < public static void main(String[] args) throws Exception< File excel = new File("C:\\Users\\Devaditya\\Documents\\Book1.xlsx"); FileInputStream fis = null; fis = new FileInputStream(excel); System.out.println(fis.toString()); HSSFWorkbook wb = new HSSFWorkbook(fis); System.out.println(wb.toString()); HSSFSheet sh = wb.getSheet("Data"); System.out.println(sh.toString()); >> 

Here i am getting the error:-

Exception in thread "main" java.io.IOException: Invalid header signature; read 0, expected -2226271756974174256 at org.apache.poi.poifs.storage.HeaderBlockReader.(HeaderBlockReader.java:88) at org.apache.poi.poifs.filesystem.POIFSFileSystem.(POIFSFileSystem.java:83) at org.apache.poi.hssf.usermodel.HSSFWorkbook.(HSSFWorkbook.java:210) at org.apache.poi.hssf.usermodel.HSSFWorkbook.(HSSFWorkbook.java:191) at demo.DemoExcel.main(DemoExcel.java:23) 

Lets start with types of WorkBook .

HSSFWorkbook

This is old binary proprietary Excel format, know by the extension .xls .

XSSFWorkbook

This is the new XML Excel format, known by the extension .xlsx .

So, you are using the wrong class.

In fact it would be better not to use a specific class at all, let POI work out what you have. Use a WorkbookFactory :

final Workbook workbook = WorkbookFactory.create(excel); 
  1. programming to the interface .
  2. robust to changes in the type of workbook read, as long a POI supports it
  3. faster and more efficient. POI can read the File piecemeal, when it needs to rather than having to slurp the whole workbook into memory.
  4. Doesn’t have the memory leak that you have when you don’t close() the FileInputStream .

try to open the file in microsoft office Excel then a pop message will appear to inform you that that file you are trying to open isn’t an excel file , and give you the choice to open it any way, so just open it and save it as Excel file .

Invalid header signature; IOException with Apache POI, java.io.IOException: Invalid header signature; read 0x000201060000FFFE, expected 0xE11AB1A1E011CFD0. when trying to add some custom properties to an Excel document using apache POI HPSF. I’m completely sure the file is Excel OLE2 (not HTML, XML or something else that Excel doesn’t …

Excel Java import issue, Invalid header signature?

I am new to Java and am having an issue importing my Excel sheet . I am trying to print out an Excel spreadsheet into the Java console using the Apache Poi library. When I run my code, I get the following exception:

java.io.IOException: invalid header signature; read 0x656D614E2C234449, expected 0xE11AB1A1E011CFD0

How can i fix it so it matches my header? Which is like this.

ID#, Name, Age, Street Address, City, State, Zip, Employer, Prescription 
//imports, blah blah, etc. public static void main( String [] args ) < try < InputStream input = new BufferedInputStream(new FileInputStream( "c:/Users/sgoetz/Desktop/Week3ProgrammingData.csv")); POIFSFileSystem fs = new POIFSFileSystem( input ); HSSFWorkbook wb = new HSSFWorkbook(fs); HSSFSheet sheet = wb.getSheetAt(0); Iterator rows = sheet.rowIterator(); while( rows.hasNext() ) < HSSFRow row = (HSSFRow) rows.next(); System.out.println("\n"); Iterator cells = row.cellIterator(); while( cells.hasNext() ) < HSSFCell cell = (HSSFCell) cells.next(); if(HSSFCell.CELL_TYPE_NUMERIC==cell.getCellType()) System.out.print( cell.getNumericCellValue()+" " ); else if(HSSFCell.CELL_TYPE_STRING==cell.getCellType()) System.out.print( cell.getStringCellValue()+" " ); else if(HSSFCell.CELL_TYPE_BOOLEAN==cell.getCellType()) System.out.print( cell.getBooleanCellValue()+" " ); else if(HSSFCell.CELL_TYPE_BLANK==cell.getCellType()) System.out.print( "BLANK " ); else System.out.print("Unknown cell type"); >> > catch ( IOException ex ) < ex.printStackTrace(); >> > 

POI — the library you are using with all the HSSF classes etc — is used to import and export Excel documents (.xls, .xlsx). You are trying to use it on a CSV document, which will not work.

I’d recommend instead a library like supercsv for that.

«Invalid header signature» is about the header that identifies the version of Excel that was used to create the Excel file. If the file is not an Excel file or is a pre-97 Excel file, you’ll get this error.

 InputStream input = new BufferedInputStream( new FileInputStream("c:/Users/sgoetz/Desktop/Week3ProgrammingData.csv")); 

I’d expect POI to actually read an Excel-format (Microsoft’s OLE 2 Compound document) file, not a .csv file.

Use POI to parse Excel but got exception «Invalid Header, I was trying to use Apache POI (Version 3.6) to parse Excel .xls file, but got only Exception: java.io.IOException: Invalid header signature; read 0x07B1FD124BEDF108, expected 0xE11AB1A1E011CFD0. I have Googled some result, which basically said that «The file is actually not a valid excel file (i.e. .csv …

Excel read error : Invalid header signature. How to resolve?

I am uploading one excel file from browser. I am using POI jar. But getting error Invalid header signature; read 3255307777713450285, expected -2226271756974174256

below the two jsp files i have used: JSP 1:

But getting the error at line POIFSFileSystem myFileSystem = new POIFSFileSystem(file);

How to resovle this problem?

You’re getting this error because your file isn’t actually an Excel .xls file, it’s something else.

I’d suggest you try opening the file in Notepad, and look at it there. Almost all errors of this type end up being that a .csv or .html file has been renamed to .xls. Excel will happily load html files (rendering the table as the spreadsheet) and csv files, and doesn’t warn you that you’ve got the wrong extension on them.

Note that if you rename a .xlsx file to a .xls and pass that to POI’s POIFSFileSystem or hssfworkbook , you’ll get a more specific error warning you that you’ve got a .xlsx file instead. You’re only getting this error because POI has absolutely no idea what your file is, only that it’s not a .xls

Just an idee, if you using maven make sure in the resource tag filtering is set to » false «. Otherwise maven tends to corrupt xls files in the copying phase

Invalid Header Signature — Opening XLS with Apache POI, I’m trying to convert a XLS file into a CSV file in java using Apache POI 3.9, however I’m getting some issues. When trying to convert the file I need to, it shows me the following error: java.io.IOException: Invalid header signature; read 0x0010000000080209, expected 0xE11AB1A1E011CFD0 at …

Invalid header signature; read 0x54535543092E4F4E, expected 0xE11AB1A1E011CFD0

ok i’m posting this after so much research, all topics having similar problems didn’t answer to mine. I received a .xls file to work with it (i cannot change its version) when i’m reading the file with poi i have a really strange behavior, it cannot read the original file: «Invalid header signature; read 0x54535543092E4F4E, expected 0xE11AB1A1E011CFD0 — Your file appears not to be a valid OLE2 document» But when i open it and save it as .xls file it works. It’s the same file with same version, only one is the original downloaded file and the other is saved manually!! can anyone explain me this, i have to work with the original excel file.

File xlsFile = new File(path); FileInputStream fis = new FileInputStream(path); Workbook workbook = new HSSFWorkbook(fis); 

That signature looks like (the start of) tab-separated data, in reverse:

Where means the actual tab character.

If it is tab-separated data, Apache POI will not be able to use it directly.

So guys i finally found the best solutions i guess to read and import data from my Tab-separated file using openCSV library, and it goes well for all types of CSV file (Character separated value) with titles, we have just to change the separator. Here is the code:

 File xlsFile = new File(path); CSVReader reader = new CSVReader(new FileReader(xlsFile), '\t'); ArrayList data = new ArrayList(); String[] nextLine; while ((nextLine = reader.readNext()) != null) < final int size = nextLine.length; //handle empty lines if (size == 0) < continue; >String debut = nextLine[0].trim(); if (debut.length() == 0 && size == 1) < continue; >data.add(nextLine); > String[] titles = data.get(0); data.remove(0); ArrayList> mappedData = new ArrayList>(data.size()); final int titlesLength = titles.length; for (String[] oneData : data) < final Mapmap = new HashMap mappedData.add(map); > 

And then we have to get values from the mappedData by their keys(titles or columns name in my case)

Apache POI «Invalid header signature» opening Excel XML, Is it possible to open an excel xml ( an xml which can open in microsoft office excel ) and it is a perfectly good xml that complies with xml spreadsheet reference I tried to use : String outputFile = «output.xml»; FileInputStream file = new FileInputStream( new File( outputFile ) ); Workbook wb …

Источник

Invalid header signature; IOException with Apache POI on excel document

If you flip the signature number round, you’ll see the bytes of the start of your file:

0x000201060000FFFE -> 0xFE 0xFF 0x00 0x00 0x06 0x01 0x02 00

The first two bytes look like a Unicode BOM, 0xFEFF means 16 bit little endian. You then have some low control bytes, the hex codes for 0 then 258 then 2, so maybe it isn’t a text file after all.

That file really isn’t an OLE2 file, and POI is right to give you the error. I don’t know what it is, but I’m guessing that perhaps it might be part of an OLE2 file without it’s outer OLE2 wrapper? If you can open it with office, do a save-as and POI should be fine to open that. As it stands, that header isn’t an OLE2 file header so POI can’t open it for you.

Solution 2

In my case, the file was a CSV file saved with the .xls extension. Excel was able to open it without a problem, but POI was not.

If I find a better/more general solution, I’ll come back and write it up here.

Solution 3

Try save it as csv file directly and use opencsv for your operations.
Use the following link to know about opencsv.
http://opencsv.sourceforge.net/#what-is-opencsv

Excel can open a csv, xls or even html table saved as xls.

So you can save the file as file_name.csv and can use opencsv for reading the file in your code.

Or else you can the file once in excel by save As excel 97-2003 workbook.

And then, POI itself can read the file 🙂

Solution 4

because you saved your file by Excel 2013. save As your file as excel 97-2003 format.

Источник

Читайте также:  Learning android and java
Оцените статью