Tag Archives: excel

[Solved] POI Read excel Error: Your InputStream was neither an OLE2 stream, nor an OOXML stream

When Java uses POI to read Excel files with XLS suffix, an error is reported:

Your InputStream was neither an OLE2 stream, nor an OOXML stream

Error code:

Workbook wb = WorkbookFactory.create(is);

Click the Create method to see the source code of POI:

public static Workbook create(InputStream inp) throws IOException, InvalidFormatException {
        if (!((InputStream)inp).markSupported()) {
            inp = new PushbackInputStream((InputStream)inp, 8);
        }

        if (POIFSFileSystem.hasPOIFSHeader((InputStream)inp)) {
            return new HSSFWorkbook((InputStream)inp);
        } else if (POIXMLDocument.hasOOXMLHeader((InputStream)inp)) {
            return new XSSFWorkbook(OPCPackage.open((InputStream)inp));
        } else {
            throw new IllegalArgumentException("Your InputStream was neither an OLE2 stream, nor an OOXML stream");
        }
    }

The haspoofshade and hasooxmlreader in the two IFS are to read the first 8 bytes of the excel file stream to determine the file information. If it is not an excel type file or a binary type file, the exception “your InputStream was neither an ole2 stream, nor an OOXML stream” will be thrown directly

Analysis:
open the problematic XLS file with sublime text text editor or Notepad + +, which is XML in text form:

Open other normal XLS files with sublime text text editor as follows, which are binary:

Reason for the problem:
the XLS file in question is actually an office openxml file, also known as spreadsheetml format (XML format of Excel). Its suffix should be XML instead of XLS. It is not a standard excel file, so it will report an error when reading with POI.

Solution:
use Excel to open the problematic XLS file, as follows:
select Yes, then save the file as XLS format, and then use POI analysis to avoid reporting errors

[Solved] Jxls error: Cannot load XLS transformer. Please make sure a Transformer implementation is in classpath

Note the problems encountered in using Jxls in the project

Cannot load XLS transformer. Please make sure a Transformer implementation is in classpath

Check whether components such as easyexcel are introduced into the project
if so, it needs to be excluded

<dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>easyexcel</artifactId>
      <version>2.2.10</version>
      <exclusions>
        <exclusion>
          <artifactId>poi</artifactId>
          <groupId>org.apache.poi</groupId>
        </exclusion>
        <exclusion>
          <artifactId>poi-ooxml</artifactId>
          <groupId>org.apache.poi</groupId>
        </exclusion>
        <exclusion>
          <artifactId>poi-ooxml-schemas</artifactId>
          <groupId>org.apache.poi</groupId>
        </exclusion>
      </exclusions>
    </dependency>

Then
the POI component 4 version is introduced

    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi</artifactId>
      <version>4.1.2</version>
    </dependency>
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml</artifactId>
      <version>4.1.2</version>
    </dependency>
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml-schemas</artifactId>
      <version>4.1.2</version>
    </dependency>

Because the project is iterative, complex excel is exported. Easyexcel can not meet the requirements. You can consider processing complex logic in the form of Jxls template.
it can solve the function of Excel processing by block, horizontal and column
official website: http://jxls.sourceforge.net/

In theory, it is not recommended to use several excel components at the same time. The idea plug-in Maven helper is recommended here to facilitate conflict handling.

When a problem is inexplicable and can not be solved by how to change it, see if there is a package conflict and if there is a problem with the network itself.

How to Solve Excel Error Log 0: Install Error

SLOVER installation manual:
① file -> More-> Options

②Add-in

③ Bottom go

④ Check solver add in and confirm to save

⑤ solver will appear in the upper right corner of the data toolbar

Error phenomenon:
the computer with 64 bit Office installed will prompt that the macro is not available after installation

even options -> Trust Center -> Credit center settings -> Macro settings -> Enable all macros and still prompt the same error.

Solution:
① the solver cannot be installed on a 64 bit computer. You can uninstall the local 64 bit office and reinstall 32-bit office.

Or

② Install VMware, build a win10, install an office 32-bit system on the virtual machine, and open network sharing and shared folders
(1) VMware installation reference: the latest super detailed VMware virtual machine download and installation
VMware official website: VMware download
(basically the default installation)

(2) Install virtual machine win10
VMware virtual machine install windows system

(3) Setting shared folders for virtual machines
VMware sets shared folders for windows virtual machines

(4) Virtual machine settings network
I found many strategies and didn’t understand
it turns out that it’s actually very simple
when the virtual machine is turned off, select Edit virtual machine settings

then select network adapter, check bridge mode and copy physical network connection status

OK, turn on the virtual machine again and find that the virtual machine can access the Internet normally

(5) the last step is the installation of 32-bit office
Microsoft Office
come to an official website link, download and install, and finish it.

How to Solve Excel Error Log 2: Sloving method

Error phenomenon: when solver uses simple LP, it cannot find a solution satisfying constraints
tips can be answered using GRG nonlinear

Solution:
GRG nonlinear is selected for the solving method

After testing, even if the constraints input expression is correct, different solving methods will report errors.

For the differences between the three solving methods:

  1. Will build a linear programming model, using the Simplex method;
  2. Solving speed: Simplex> GRG> Evolutionary
  3. GRG may not get the global optimal solution, use Evolutionary to get the global optimal solution;
  4. Using GRG combined with Multistart can get a better local optimal solution.

in short, when an error is reported, if there is no problem with the constraints after the inspection, change the solving method

Tencent cloud container easyexcel export excel error NoClassDefFoundError: could not initialize class sun.awt.x11fontmanager

Development environment:

springboot 2.4.3easyexcel 2.2.7jdk8


Problem Description:

1. There is no local problem. An error was reported after the release of Tencent cloud container.

        EasyExcel.write(response.getOutputStream(), ViewDatass.class).sheet("xxx明细").doWrite(datas);

2. Error report log

[Request processing failed; nested exception is com.alibaba.excel.exception.ExcelGenerateException: java.lang.NoClassDefFoundError: Could not initialize class sun.awt.X11FontManager] with root cause
java.lang.NoClassDefFoundError: Could not initialize class sun.awt.X11FontManager
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Class.java:348)
        at sun.font.FontManagerFactory$1.run(FontManagerFactory.java:82)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.font.FontManagerFactory.getInstance(FontManagerFactory.java:74)
        at java.awt.Font.getFont2D(Font.java:491)
        at java.awt.Font.canDisplayUpTo(Font.java:2060)
        at java.awt.font.TextLayout.singleFont(TextLayout.java:470)
        at java.awt.font.TextLayout.<init>(TextLayout.java:531)
        at org.apache.poi.ss.util.SheetUtil.getDefaultCharWidth(SheetUtil.java:275)
        at org.apache.poi.xssf.streaming.AutoSizeColumnTracker.<init>(AutoSizeColumnTracker.java:117)
        at org.apache.poi.xssf.streaming.SXSSFSheet.<init>(SXSSFSheet.java:82)
        at org.apache.poi.xssf.streaming.SXSSFWorkbook.createAndRegisterSXSSFSheet(SXSSFWorkbook.java:658)
        at org.apache.poi.xssf.streaming.SXSSFWorkbook.createSheet(SXSSFWorkbook.java:679)
        at org.apache.poi.xssf.streaming.SXSSFWorkbook.createSheet(SXSSFWorkbook.java:90)
        at com.alibaba.excel.util.WorkBookUtil.createSheet(WorkBookUtil.java:66)
        at com.alibaba.excel.context.WriteContextImpl.createSheet(WriteContextImpl.java:205)
        at com.alibaba.excel.context.WriteContextImpl.initSheet(WriteContextImpl.java:185)
        at com.alibaba.excel.context.WriteContextImpl.currentSheet(WriteContextImpl.java:122)
        at com.alibaba.excel.write.ExcelBuilderImpl.addContent(ExcelBuilderImpl.java:53)
        at com.alibaba.excel.ExcelWriter.write(ExcelWriter.java:161)
        at com.alibaba.excel.ExcelWriter.write(ExcelWriter.java:146)
        at com.alibaba.excel.write.builder.ExcelWriterSheetBuilder.doWrite(ExcelWriterSheetBuilder.java:61)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:197)
        at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:141)
        at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:894)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
        at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1060)
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:962)
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
        at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:626)
        at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)

Cause analysis:

There is no local error report. When you publish it to Tencent cloud container, you can report an error. If you look at the prompt, it should be a certain font. As a result, Excel can’t render it. Interestingly, there are several errors reported in the middle, which leads to many detours…

com.alibaba.excel.exception.ExcelGenerateException: java.lang.UnsatisfiedLinkError: /usr/local/java/xxx/jre/lib/amd64/libfontmanager.so: libfreetype.so.6: cannot open shared object file: No such file or directory

Solution:

The problem is solved by adding fonts to the docker file.

# Add font
RUN yum install dejavu-sans-fonts fontconfig -y

Java will convert Excel to list set or JSON, export excel file to local, excel import and export, easyexcel tool class

Introducing Maven coordinates

        <!--fastjson-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.76</version>
        </dependency>        
        <!--easyexcel-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>2.2.8</version>
        </dependency>

According to the file path, the excel file is parsed into a list

    /**
     * Parsing Excel files into Lists
     *
     * @param pathName file path (e.g. D:\test\xzh.xlsx)
     * @param head Table header
     * @param <T> generic
     * @return
     */
    public static <T> List<T> upload(String pathName, Class<T> head) {
        List<T> list = new ArrayList<>();
        AnalysisEventListener<T> analysisEventListener = new AnalysisEventListener<T>() {
            // This will be called for every data parsing
            @Override
            public void invoke(T data, AnalysisContext context) {
                log.info("Parsing a piece of data:{}", JSON.toJSONString(data));
                list.add(data);
                // TODO Here you can also manipulate the data
            }

            // All the data parsing is done and will be called
            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {
                log.info("All data parsing is complete!") ;
                // TODO Here you can also manipulate the data
            }
        };
        EasyExcel.read(pathName, head, analysisEventListener).sheet().doRead();
        return list;
    }

According to the file stream, the excel file is parsed into a list

    /**
     * Parsing Excel files into Lists
     *
     * @param file File
     * @param head table header
     * @param <T> generic
     * @return
     */
    public static <T> List<T> upload(MultipartFile file, Class<T> head) {
        List<T> list = new ArrayList<>();
        AnalysisEventListener<T> analysisEventListener = new AnalysisEventListener<T>() {
            // This will be called every time the data is parsed
            @Override
            public void invoke(T data, AnalysisContext context) {
                log.info("Parsed a piece of data: {}", JSON.toJSONString(data));
                list.add(data);
                // TODO You can also manipulate the data here
            }

            // All the data parsing is done and it will call
            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {
                log.info("All data parsing is complete!") ;
                // TODO Here you can also manipulate the data
            }
        };
        InputStream inputStream;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            log.error("upload-InputStream-Exception:", e);
            return null;
        }
        EasyExcel.read(inputStream, head, analysisEventListener).sheet().doRead();
        return list;
    }

Download excel file to file path

    /**
     * Excel file download
     *
     * @param pathName File path
     * @param sheetName Worksheet name
     * @param data data
     * @param head Table header
     * @param <T> generic
     */
    public static <T> void download(String pathName, String sheetName, List<T> data, Class<T> head) {
        EasyExcel.write(pathName, head).sheet(sheetName).doWrite(data);
    }

Excel file download to file path response body response

    /**
     * Excel file download
     *
     * @param response response body
     * @param excelName File name
     * @param sheetName Worksheet name
     * @param data data
     * @param head table header
     * @param <T> generic
     */
    public static <T> void download(HttpServletResponse response, String excelName, String sheetName, List<T> data, Class<T> head) {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("UTF-8");
        try {
            String fileName = URLEncoder.encode(excelName, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), head).sheet(sheetName).doWrite(data);
        } catch (IOException e) {
            log.error("download-Exception:", e);
        }
    }

GitHub: https://github.com/xxiangzh/xzh-excel/tree/easyexcel

Remove spaces after characters in Excel cells

    Code value (obtained by the CODE function) In the range 1-255, there are 148 invisible characters 1-15,28-32,127-254. Clean (A1) can be used to remove characters with code value less than or equal to 31 (including visible characters 16-27) and characters with code value equal to 128. Substitute (A1,CHAR(32),””) function can remove invisible characters whose code value is equal to 32 and 129-254, and TRIM function can remove such characters at both ends of the string. Invisible characters with code value equal to 127 can only be removed using the SUBSTITUTE(A1,CHAR(127),””) function. Using both functions together, you can basically remove all invisible characters with code values less than 255 (including visible characters with code values 16-27):
    SUBSTITUTE(SUBSTITUTE(CLEAN(A1),CHAR(32),””),CHAR(127),””)

VC + + COM programming error of 0xc0000005: access conflict when reading location 0xfeefef6

Calling COM+ gives you the desired result and returns an error after the last return 0 sentence.

error location in comip.h

void _Release() throw()

{

if (m_pInterface! = NULL) {

m_pInterface – & gt; Release(); // Error reported here

}

}
When I encounter this problem myself, I use m_pInterface->; Release(); Comment out the program no longer reports an error.
Some other ways online:
1.m_pInterface-> Release () into m_pInterface = NULL from http://topic.csdn.net/u/20091120/16/8a9c8d91-9a39-416b-8d8d-8c2cd2a71d3e.html
2. In the program implementation: PTR ->; Release(); To PTR. Release (); From http://topic.csdn.net/u/20091120/16/8a9c8d91-9a39-416b-8d8d-8c2cd2a71d3e.html
3. One statement is that it is a matter of scope. I don’t know much about it. See: http://stackoverflow.com/questions/2653797/why-does-couninitialize-cause-an-error-on-exit
This method has been tried, but it also works. See the following instructions for details.

I’m working on a C++ application to read some data from an Excel file. I’ve got it working, but I’m confused about one part. Here’s the code (simplified to read only the first cell).

//Mostly copied from http://www.codeproject.com/KB/wtl/WTLExcel.aspx 
 
#import "c:\Program Files\Common Files\Microsoft Shared\OFFICE11\MSO.DLL" 
#import "c:\Program Files\Common Files\Microsoft Shared\VBA\VBA6\VBE6EXT.OLB" 
#import "C:\Program Files\Microsoft Office\Office11\excel.exe" rename ("DialogBox","ExcelDialogBox") rename("RGB","ExcelRGB") rename("CopyFile", "ExcelCopyFile") rename("ReplaceText", "ExcelReplaceText") exclude("IFont", "IPicture") 
 
_variant_t varOption((long) DISP_E_PARAMNOTFOUND, VT_ERROR); 
 
int _tmain(int argc, _TCHAR* argv[]) 
{ 
    DWORD dwCoInit = 0; 
    CoInitializeEx(NULL, dwCoInit); 
    Excel::_ApplicationPtr pExcel;     
    pExcel.CreateInstance(_T("Excel.Application")); 
    Excel::_WorkbookPtr pBook; 
    pBook = pExcel->Workbooks->Open("c:\\test.xls", varOption, varOption, varOption, varOption, varOption, varOption, varOption, varOption, varOption, varOption, varOption, varOption); 
    Excel::_WorksheetPtr pSheet = pBook->Sheets->Item[1]; 
    Excel::RangePtr pRange = pSheet->GetRange(_bstr_t(_T("A1"))); 
    _variant_t vItem = pRange->Value2; 
    printf(_bstr_t(vItem.bstrVal));     
    pBook->Close(VARIANT_FALSE); 
    pExcel->Quit(); 
    //CoUninitialize(); 
    return 0; 
} 

I had to comment out the call to CoUninitialize for the program to work. When CoUninitialize is uncommented, I get an access violation in the _Release function in comip.h on program exit.
Here’s the code from comip. h, for what it’s worth.

void _Release() throw() 
{ 
    if (m_pInterface != NULL) { 
        m_pInterface->Release(); 
    } 
} 

I’m not very experienced with COM programming, so there’s probably something obvious I’m missing.

    Why does the call to CoUninitialize cause an exception? What are the consequences of not calling CoUninitialize? Am I doing something completely wrong here?

ANSWER!

The problem you are having is one of scope. The short answer is to move the CoInit and CoUninit into an outer scope from the Ptrs. For example:

//Mostly copied from http://www.codeproject.com/KB/wtl/WTLExcel.aspx 
 
#import "c:\Program Files\Common Files\Microsoft Shared\OFFICE11\MSO.DLL" 
#import "c:\Program Files\Common Files\Microsoft Shared\VBA\VBA6\VBE6EXT.OLB" 
#import "C:\Program Files\Microsoft Office\Office11\excel.exe" rename ("DialogBox","ExcelDialogBox") rename("RGB","ExcelRGB") rename("CopyFile", "ExcelCopyFile") rename("ReplaceText", "ExcelReplaceText") exclude("IFont", "IPicture") 
 
_variant_t varOption((long) DISP_E_PARAMNOTFOUND, VT_ERROR); 
 
int _tmain(int argc, _TCHAR* argv[]) 
{ 
    DWORD dwCoInit = 0; 
    CoInitializeEx(NULL, dwCoInit); 
    { 
        Excel::_ApplicationPtr pExcel;     
        pExcel.CreateInstance(_T("Excel.Application")); 
        Excel::_WorkbookPtr pBook; 
        pBook = pExcel->Workbooks->Open("c:\\test.xls", varOption, varOption, varOption, varOption, varOption, varOption, varOption, varOption, varOption, varOption, varOption, varOption); 
        Excel::_WorksheetPtr pSheet = pBook->Sheets->Item[1]; 
        Excel::RangePtr pRange = pSheet->GetRange(_bstr_t(_T("A1"))); 
        _variant_t vItem = pRange->Value2; 
        printf(_bstr_t(vItem.bstrVal));     
        pBook->Close(VARIANT_FALSE); 
        pExcel->Quit(); 
    } 
    CoUninitialize(); 
    return 0; 
} 

The longer answer is that the Ptrs destructors (which calls Release) are being called on exit from main. This is after CoUnit which, basically, shuts down the communication channel between your app and the COM object.
What are the consequences of not calling CoUnit?For short lived in-process COM servers, there really isn’t any negative consequence.

POI set excel cell background color (use of setfillforegrondcolor and setfillpattern)

    IndexedColors.AQUA.getIndex()IndexedColors.AUTOMATIC.getIndex()IndexedColors.BLUE.getIndex()IndexedColors.BLUE_GREY.getIndex()IndexedColors.BRIGHT_GREEN.getIndex()IndexedColors.BROWN.getIndex()Ind exedColors.CORAL.getIndex()IndexedColors.CORNFLOWER_BLUE.getIndex()IndexedColors.DARK_BLUE.getIndex()IndexedColors.DARK_GREEN.getIndex()IndexedColors.DARK_RED.getIndex()IndexedColors.DARK_TEAL.getInde x()IndexedColors.DARK_YELLOW.getIndex()IndexedColors.GOLD.getIndex()IndexedColors.GREEN.getIndex()IndexedColors.GREY_25_PERCENT.getIndex()IndexedColors.GREY_40_PERCENT.getIndex()IndexedColors.GREY_50_ PERCENT.getIndex()IndexedColors.GREY_80_PERCENT.getIndex()IndexedColors.INDIGO.getIndex()IndexedColors.LAVENDER.getIndex()IndexedColors.LEMON_CHIFFON.getIndex()IndexedColors.LIGHT_BLUE.getIndex()Index edColors.LEMON_CHIFFON.getIndex()IndexedColors.LIGHT_BLUE.getIndex()IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex()IndexedColors.LIGHT_GREEN.getIndex()IndexedColors.LIGHT_ORANGE.getIndex()IndexedColors .LIGHT_TURQUOISE.getIndex()IndexedColors.LIGHT_YELLOW.getIndex()IndexedColors.LIME.getIndex()IndexedColors.MAROON.getIndex()IndexedColors.OLIVE_GREEN.getIndex()IndexedColors.ORANGE.getIndex()IndexedCo lors.ORCHID.getIndex()IndexedColors.PALE_BLUE.getIndex()IndexedColors.PINK.getIndex()IndexedColors.PLUM.getIndex()IndexedColors.RED.getIndex()IndexedColors.ROSE.getIndex()IndexedColors.ROYAL_BLUE.getI ndex()IndexedColors.SEA_GREEN.getIndex()IndexedColors.SKY_BLUE.getIndex()IndexedColors.TAN.getIndex()IndexedColors.TEAL.getIndex()IndexedColors.TURQUOISE.getIndex()IndexedColors.VIOLET.getIndex()Index EdColors. WHITE. GetIndex IndexedColors ()// WHITE. YELLOW. GetIndex ()

There was a problem sending the command to the program in Excel 2010

Environment: MicroSoft Excel 2010
Sending the Command to the program was a problem.

As shown in figure:


Solution: open Excel– & GT; File — — — — — — — — & gt; Options — — — — — — — — & gt; Senior — — — — — — — — & gt; Drop this check (ignoring other applications that use dynamic database exchange (DDE)) -& GT; To solve.
 
As shown in figure:


Resources:
http://support.microsoft.com/kb/211494
http://blog.sina.com.cn/s/blog_4988d99a0100u86i.html