qax-os / excelize

Go language library for reading and writing Microsoft Excel™ (XLAM / XLSM / XLSX / XLTM / XLTX) spreadsheets
https://xuri.me/excelize
BSD 3-Clause "New" or "Revised" License
17.64k stars 1.69k forks source link

Open a Microsoft Excel sheet which been set password, in code not provide “Options” cause “zip: not a valid zip file” #1877

Closed xjxl520303 closed 2 months ago

xjxl520303 commented 2 months ago

Create a new Excel use Microsoft Office Excel 2019, and set password, then use excelize.OpenFile("your path"), if I not provide password It throws the error 2024/04/16 20:17:46 zip: not a valid zip file. But when I set password with code f, err := excelize.OpenFile("E:/ExcelDemo/testPanic.xlsx", excelize.Options{Password: "qwerty"}), it works well. So I think it should match the error ErrWorkbookPassword is expected result.

xuri commented 2 months ago

Thanks for your issue. The unencrypted workbook is a compressed file with the ZIP format, but the encrypted workbook is a CFB (OLE) file, which is different from the ZIP format. You will get that error message not only after opening an encrypted workbook without specifying the correct password but also after opening any file format that isn't supported by this library. So I think this error message is expected. Note that, you can roughly determine if a file is in a CFB format by this identifier. I'll close this issue. If you have any questions, please let me know, and you can reopen this anytime.

xjxl520303 commented 2 months ago

Thank you, @xuri, I add a function to judge whether it is an ole format Excel file, and tips it has encrypted must provide password to open it.

func isOleExcel(f io.ReadSeeker) bool {
    oleIdentifier := []byte{0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1}
    buf := make([]byte, len(oleIdentifier))

    _, err := f.Read(buf)

    if err != nil {
        return false
    }

    f.Seek(0, io.SeekStart)

    return bytes.Compare(buf, oleIdentifier) == 0
}