Code Monkey home page Code Monkey logo

fastexcel's Introduction

fastexcel

Build Status Coverage Status Maven Central Javadocs

fastexcel-writer

There are not many alternatives when you have to generate xlsx Excel workbooks in Java. The most popular one (Apache POI) includes many features, but when it comes down to huge worksheets it quickly becomes a memory hog.

Its streaming API may mitigate this problem but it introduces several limitations:

  • Its sliding window mechanism prevents you from accessing cells above the current writing position.
  • It writes stuff to a temporary file.
  • It comes with an overhead on the file size because shared strings are disabled by default. Enabling shared strings is likely to consume much more heap if you deal with string values.

So, fastexcel has been created to offer an alternative with the following key points:

  • Limited set of features (basic style support, no graph support yet) and very simple API.
  • Reduced memory footprint and high performance by accumulating only necessary elements. XML stuff is piped to the output stream at the end.
  • Multithreading support: each worksheet in the workbook can be generated by a different thread, while fully supporting shared strings and styles.

Benchmark

In this simple benchmark test, we generate a workbook with a single worksheet containing 100,000 rows and 4 columns. Apache POI (non-streaming) is about 10 times slower than fastexcel and uses 12 times more heap memory. The streaming API of Apache POI is almost on par with fastexcel in terms of performance and uses less heap just because it keeps only 100 rows in memory: see related limitations in the paragraph above.

Generation time

Heap memory usage

Note heap memory usage is measured just before flushing the workbook to the output stream.

Prerequisites

  • Java 8+. Build with Maven.
  • Include the following dependency in your POM:
<dependency>
    <groupId>org.dhatim</groupId>
    <artifactId>fastexcel</artifactId>
    <version>0.18.0</version>
</dependency>

Examples

The javadoc for the last release is available here.

Simple workbook

Create a workbook with a single worksheet and a few cells with the different supported data types.

try (OutputStream os = ..., Workbook wb = new Workbook(os, "MyApplication", "1.0");) {
    Worksheet ws = wb.newWorksheet("Sheet 1");
    ws.value(0, 0, "This is a string in A1");
    ws.value(0, 1, new Date());
    ws.value(0, 2, 1234);
    ws.value(0, 3, 123456L);
    ws.value(0, 4, 1.234);
}

Set properties

General properties:

wb.properties()
    .setTitle("title property")
    .setCategory("category property")
    .setSubject("subject property")
    .setKeywords("keywords property")
    .setDescription("description property")
    .setManager("manager property")
    .setCompany("company property")
    .setHyperlinkBase("hyperlinkBase property");

Custom properties:

wb.properties()
    .setTextProperty("Test TextA", "Lucy")
    .setTextProperty("Test TextB", "Tony")
    .setDateProperty("Test DateA", Instant.parse("2022-12-22T10:00:00.123456789Z"))
    .setDateProperty("Test DateB", Instant.parse("1999-09-09T09:09:09Z"))
    .setNumberProperty("Test NumberA", BigDecimal.valueOf(202222.23364646D))
    .setNumberProperty("Test NumberB", BigDecimal.valueOf(3.1415926535894D))
    .setBoolProperty("Test BoolA", true)
    .setBoolProperty("Test BoolB", false);

Styles and formatting

Change cell style to bold with a predefined fill pattern:

ws.style(0, 0).bold().fill(Fill.GRAY125).set();

Apply formatting to a cell containing a timestamp:

ws.value(0, 0, LocalDateTime.now());
ws.style(0, 0).format("yyyy-MM-dd H:mm:ss").set();

Apply conditional formatting of expression type to a cell:

ws.style(0, 0).fillColor("FF8800").set(new ConditionalFormattingExpressionRule("LENB(A1)>1", true));

Rotate text in cell:

ws.style(0, 0).rotation(90).set();

Set global default font:

wb.setGlobalDefaultFont("Arial", 15.5);

Cell ranges

Set style on a range of cells:

ws.range(0, 0, 10, 10).style().horizontalAlignment("center").italic().set();

Merge cells:

ws.range(0, 0, 10, 10).merge();

Shade alternate rows:

ws.range(0, 0, 10, 10).style().shadeAlternateRows(Color.GRAY2).set();

or shade every Nth row (e.g. every 5th):

ws.range(0, 0, 10, 10).style().shadeRows(Color.GRAY2, 5).set();

Name a cell range (name of a cell range can only include letters, numbers and underscore):

ws.range(0, 0, 0, 10).setName("header");

Formulas

Note the cells with a formula do not have a value in the generated workbook.

ws.formula(10, 0, "SUM(A1:A10)");
// With Range.toString():
ws.formula(10, 0, "SUM(" + ws.range(0, 0, 9, 0).toString() + ")");

Hyperlink

Insert a hyperlink to a cell or range of cells.

ws.hyperlink(0, 0, new HyperLink("https://github.com/dhatim/fastexcel", "Baidu"));
ws.range(1, 0, 1, 1).setHyperlink(new HyperLink("./dev_soft/test.pdf", "dev_folder"));

Inline String

The function value(row, col, string) sets the value as a shared string. If there are many duplicate strings, using a shared string can be very efficient in terms of file size. However, if there are many distinct strings, using shared strings can consume a large amount of memory to share these strings. Therefore, you may choose not to share strings to use less memory, even if the file size will be large. In this case, you can use inline strings.

ws.inlineString(0, 0, "Inline String");

Data Table

ws.range(0, 0, 5, 2).createTable()
                        .setDisplayName("TableDisplayName")
                        .setName("TableName")
                        .styleInfo()
                        .setStyleName("TableStyleMedium1")
                        .setShowLastColumn(true);

Additional worksheet features

Set tab color

ws.setTabColor("F381E0");

To keep the sheet in active tab:

ws.keepInActiveTab();

Set paper size and page orientation (visible in print preview mode):

ws.paperSize(PaperSize.A4_PAPER);
ws.pageOrientation("landscape");

Set bottom, top, left, or right margin:

ws.leftMargin(0.3);
ws.bottomMargin(0.2);

Create a freeze pane (some rows and columns will be kept still while scrolling).
To freeze the first column on the left and the top three rows:

ws.freezePane(1, 3);

Define repeating rows or columns for the print setup.

ws.repeatRows(0, 4); // keep first top 5 rows on each page when printing.
ws.repeatRows(2); // keep the third row on each page when printing.

ws.repeatCols(0, 2); // repeat first three columns (A to C) on each page when printing.
ws.repeatCols(0); // repeat only first column (A) on each page for the print setup.

Hide sheet.

ws.setVisibilityState(VisibilityState.HIDDEN);

Hide rows or colums

ws.hideRow(2);
ws.hideColumn(2);
IntStream.rangeClosed(3,5).forEach(ws::hideRow);
IntStream.rangeClosed(3,5).forEach(ws::hideColumn);

Hide grid lines

ws.hideGridLines();

Display the worksheet from right to left

ws.rightToLeft();

Group rows or columns

ws.groupRows(23);
ws.groupRows(15);

ws.groupCols(23);
ws.groupCols(15);

Indicating summary rows/columns appear direction

ws.rowSumsBelow(false);
ws.rowSumsRight(false);

Set header and footer content.
To set page enumeration in the top right:

ws.header("page 1 of ?", Position.RIGHT);

To set custom text in the footer (bottom left):

ws.footer("Generated with Fastexcel", Position.LEFT, "Arial", 10);

To provide sheetname in the bottom central position:

ws.footer("sheetname", Position.CENTER, 8);

To set firstPageNumber to 2 (default is 0):

ws.firstPageNumber(2);

To remove any cell background color or font color for the print setup: (this does not apply to printer color settings, only removes any colored rows etc. - see in print preview)

ws.printInBlackAndWhite();

To revert back the colors for the print setup:

ws.printInColor();

To set the scaling factor to 60 % for the print setup:

ws.pageScale(60);

To enable autoPageBreaks:

ws.setAutoPageBreaks(true);

To set fitToPage:

ws.setFitToPage(true);

To set fitToWidth to 2 pages with unlimited number of rows:

ws.setFitToPage(true);
ws.fitToWidth(2);
ws.fitToHeight(999);

Multithreaded generation

Each worksheet is generated by a different thread.

try (OutputStream os = ...;  Workbook wb = new Workbook(os, "MyApplication", "1.0");) {
    Worksheet ws1 = wb.newWorksheet("Sheet 1");
    Worksheet ws2 = wb.newWorksheet("Sheet 2");
    CompletableFuture<Void> cf1 = CompletableFuture.runAsync(() -> {
        // Fill worksheet 1
        ...
    });
    CompletableFuture<Void> cf2 = CompletableFuture.runAsync(() -> {
        // Fill worksheet 2
        ...
    });
    CompletableFuture.allOf(cf1, cf2).get();
}

fastexcel-reader

The reader part of fastexcel is a streaming alternative of Apache POI. It only reads cell content. It discards styles, graphs, and many other stuff. The API is simplier than streaming API of Apache POI.

Benchmarks

In this simple benchmark test, we read a workbook of 65536 lines. We see that Apache Poi (non-streaming) is about 10x times slower than fastexcel read. The streaming API of Apache POI is about 2x times slower. In between there a more developer friendly wrapper around Apache Poi called Excel Streaming Reader (xlsx-streamer).

Reading time

Prerequisites

  • Java 8+. Build with Maven.
  • Include the following dependency in your POM:
<dependency>
    <groupId>org.dhatim</groupId>
    <artifactId>fastexcel-reader</artifactId>
    <version>0.18.0</version>
</dependency>

Examples

Simple reading

Open a workbook and read all rows in a streaming way.

try (InputStream is = ...; ReadableWorkbook wb = new ReadableWorkbook(is)) {
    Sheet sheet = wb.getFirstSheet();
    try (Stream<Row> rows = sheet.openStream()) {
        rows.forEach(r -> {
            BigDecimal num = r.getCellAsNumber(0).orElse(null);
            String str = r.getCellAsString(1).orElse(null);
            LocalDateTime date = r.getCellAsDate(2).orElse(null);
        });
    }
}

You can read all rows to a list with:

List<Row> rows = sheet.read();

Iterate on row to get all cells.

Row row = ...;
row.forEach(cell -> {
    ...
});

More Information

Reading and Writing of encryption-protected documents

This project does not implement read-write encryption protected excel documents, but it can be realized by combining poi and poi-ooxml. This test class is a reference implementation : EncryptionTest

fastexcel's People

Contributors

albatarm avatar ant38 avatar apptaro avatar autocomplete1 avatar brocololo avatar catdog2 avatar charphi avatar d22 avatar dependabot[bot] avatar dorssar avatar dplusic avatar ewingrj avatar ezand avatar gmulders avatar gpsfl avatar jjmin321 avatar meimingle avatar mgomm avatar mumairofficial avatar ochedru avatar olivierchedru avatar outofcoffeeerror avatar pjfanning avatar r3mv avatar renovate[bot] avatar rgbj avatar rzymek avatar sz-blacky avatar zorglube avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fastexcel's Issues

Suggestion: Return null instead of throwing OutOfBoundsException when reading Cells from Row

First of all, I really appreciate the work that went into this!

I'm parsing a xlsx with 36 columns or so, and the last few columns represent optional data. As such, them being empty/null is a valid state.

However, when I read a cell that is null, and all following columns of that row are also null, "OutOfBoundsException" is thrown.

As per the Excel specs, the maximum column number is 16,384.

If feasible, I propose throwing "OutOfBoundsException", when the column index greater than 16,384 is requested, and otherwise return null on absent values.

Cheers

Read percentage and currency

Facing problem while reading percentage (ex: 68% in excel file converted to 0.68), currency sign not supported also

Continuously stream rows

I started using this library because I thought that it continuously streamed values to the OutputStream passed to the Workbook instance. This doesn't seem to be the case, rather it accumulates all data in memory and when calling ws.finish() everything is written to the OutputStream. I'm sure that this is intended behavior but when you're working with a huge set of rows you don't want to keep everything in memory and rather just pipe it to the output stream directly. Would this be out of scope for the project?

Proposal: Add support for notes

Hello,

I am building a basic diff&mege tool for excel files, and I am looking for support of read/write on Cell.Notes so that users can add notes to their "conflict resolution" on cells.

Do you have any guidelines for contribution ?
Are you open to incorporate note support ? It might seem like a good feature that should not affect performance as I assume (not a raw excel format expert..) might be easy to do lazily,

Thanks

IndexOutOfBoundsException during reading xlsx in a streaming way

Try to read xlsx file and get IndexOutOfBoundsException after full file reading.
For example, if I run this code:

Sheet sheet = wb.getFirstSheet();
            try (Stream<Row> rows = sheet.openStream()) {
                rows.forEach(r -> {
                    System.out.println(r.getRowNum());
                });
            }

For attached file, I get strange output:

1
2
1039685
java.lang.IndexOutOfBoundsException: row-index: 1039685, index: 0, count: 0
	at org.dhatim.fastexcel.reader.Row.getCell(Row.java:41)
	at com.checker.springbootadminclient.temp.translations.Sql3.lambda$main$0(Sql3.java:36)
	at org.dhatim.fastexcel.reader.RowSpliterator.tryAdvance(RowSpliterator.java:52)
	at java.base/java.util.Spliterator.forEachRemaining(Spliterator.java:326)
	at java.base/java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:658)
	at com.checker.springbootadminclient.temp.translations.Sql3.main(Sql3.java:34)

In the same time, rows.count() return correct result.

Translations.xlsx

fully streaming reader

Currently new ReadableWorksheet(InputStream) will read the whole uncompressed xml data into memory. This is how OPCPackage.open(InputStream) works.

It would be great to make fastexcel-reader be able to stream rows as it reads the input stream.

Usually the order of xml files in the xlsx archive is as follows:

-rw----     2.0 fat      571 bl defN 17-Aug-16 12:30 _rels/.rels
-rw----     2.0 fat      271 bl defN 17-Aug-16 12:30 docProps/app.xml
-rw----     2.0 fat      588 bl defN 17-Aug-16 12:30 docProps/core.xml
-rw----     2.0 fat      549 bl defN 17-Aug-16 12:30 xl/_rels/workbook.xml.rels
-rw----     2.0 fat     2725 bl defN 17-Aug-16 12:30 xl/sharedStrings.xml
-rw----     2.0 fat    43085 bl defN 17-Aug-16 12:30 xl/worksheets/sheet1.xml
-rw----     2.0 fat     5637 bl defN 17-Aug-16 12:30 xl/styles.xml
-rw----     2.0 fat      716 bl defN 17-Aug-16 12:30 xl/workbook.xml
-rw----     2.0 fat     1111 bl defN 17-Aug-16 12:30 [Content_Types].xml

This is great and would allow processing on the fly. The zip could be read using ZipInputStream. Shared string table would be created from sharedStrings.xml when it would be encountered. Then rows would be emitted to the user are they are read from sheet1.xml. In this mode accessing sheets would only be allowed in order in which they appear in the archive.

There is one problematic case though. I have already came across an xlsx (saved from MS Excel) where xl/sharedStrings.xml appeared after xl/worksheets/sheet1.xml, like this:

-rw----     2.0 fat      571 bl defN 17-Aug-16 12:30 _rels/.rels
-rw----     2.0 fat      271 bl defN 17-Aug-16 12:30 docProps/app.xml
-rw----     2.0 fat      588 bl defN 17-Aug-16 12:30 docProps/core.xml
-rw----     2.0 fat      549 bl defN 17-Aug-16 12:30 xl/_rels/workbook.xml.rels
-rw----     2.0 fat    43085 bl defN 17-Aug-16 12:30 xl/worksheets/sheet1.xml
-rw----     2.0 fat     2725 bl defN 17-Aug-16 12:30 xl/sharedStrings.xml
-rw----     2.0 fat     5637 bl defN 17-Aug-16 12:30 xl/styles.xml
-rw----     2.0 fat      716 bl defN 17-Aug-16 12:30 xl/workbook.xml
-rw----     2.0 fat     1111 bl defN 17-Aug-16 12:30 [Content_Types].xml

I do hope xl/_rels/workbook.xml.rels always appear before sheet and sharedStrings. This would at least allow for detection of this case: If sharedString.xml is specified in rels and sheet.xml is encountered before sharedString in the zip.
The only one solution that comes to my mind. Put aside the raw compressed sheet1.xml part of the input stream to temporary file. Then when sharedString.xml is read from input stream, resume uncompressing sheet1.xml and processing in on the fly then.

Further possible optimizations:
  • Skip xlsx entries that we're not parsing anyway without uncompressing them (docProps/app.xml, xl/styles.xml)
  • Instead of saving compressed sheet.xml to temp file, start with putting is aside in memory. Then save to file only after some threshold is reached.
  • Fully skip sheets.xml that the user is not interested in. For example: Using InputStream source; The user asks for sheet3.xml (that is after name to id resolution). sheet1 and sheet2 are skipped, uncompressed when reading the InputStream. Only when sheet3.xml is encounted, it is processed and rows streamed to the users. Accessing sheet1 or sheet2 after that would be not possible.
Simpler alternative:

Load the whole InputStream (compressed xlsx) into memory.
Then specific parts like sharedString.xml or sheet3.xml could be
accessed using the zip's central directory that is located at the end of the archive.
(see "Zip file structure" in https://rzymek.github.io/post/excel-zip64/).
Maybe OPCPackage has a mode that works this way already.
OPCPackage.open(ZipEntrySource)?
If not, a contribution to OPCPackage might be a better place for improvement.

What do you think?

No ability to set a border only from one side of cell

There are only two methods fro borders in StyleSetter class, and they apply the border styles from all sides
ex:

image

here is result:
image

Can you add ability to define border styles for only one side, for ex for bottom or left, i want to get result like this.

image

Thank You.

Support for adding hyperlinks

Some other libraries support adding Hyperlinks. As I am migrating an older project from Apache Poi to fastexcel, I would be gracious for the addition of such a functionality.

image

Issue when open xls file

Hi,
When open the xls file. it throws the following error dialogue box. Kindly provide the solution as soon as possible.

thirddialogueerror
seconddialougeerror2
firstdialougeerror1

excel 2013 is not opening the generated xlsx file

Dear Team,
I am unable to open the generated Excel file ( xlsx file), where some of the cell has null values . PLease see the code snippet below.

if(value != null) {
sheet.value((i+1), j, ObjectUtils.toString(value));
}else {
sheet.value((i+1), j, null);
}

		//Writing the excel to a file.
		FileOutputStream outputStream = new FileOutputStream(fileName);
		try {
			os.writeTo(outputStream);
			 
		}catch (Exception e) {
			logger.error("error in writing excel file",e);
		}finally {
			outputStream.close();
                    if(workbook != null) {
			workbook.finish();
		}
}

fileformat_xlsx

Bordercolor not working

Hi,

Border color not working using this method. Please help me.
ws.style(i, j).bold().fontSize(9).borderColor(BorderSide.BOTTOM,"FF0000").set();

Support to create links to documents

Local links to documents are not possible with the =HYPERLINK....
Would be a great enhancement
my usecase
I need a function to make a clickable link to some cells which opens a pdf.

Support for Boolean cell type

Hello.
Currently I'm getting error on creating cell with Boolean value: "No supported cell type for class java.lang.Boolean".

Database: MySQL
Column Type: TINYINT(1)
Library: mysql-connector-java
Library Version: 8.0.13

Thank you for your time.

Write doc for reader

There is no documentation for module fastexcel-reader. We need at least a few examples in the readme.

excel 2007 can't open fastexcel generate xlsx file

dear sir/madam:
i'm using fastexcel 0.8.1 to generate xlsx file,i found excel 2007 can't open the result file collect,
the low version excel can't recognition the attribute <cols autoFit=\"true\">.
set the width of the column, the excel 2007 normal xml format is as follows:
<cols> <col min="1" max="1" width="21.375" customWidth="1"/> <col min="4" max="4" width="30.875" customWidth="1"/> </cols>

Bug parsing Dates?

I'm having trouble reading dates from excel file. FastExcel doesn't recognize DATE type fields so it parses them as NUMBER instead and gives me something like 40333.
I don't have this problem with Apache POI.

Cannot open output in Libreoffice

I'm unable to open output in LibreOffice Calc from a simple test case from fastexcel-writer 0.10.7:

public class FastExcelTest {

    @Test
    public void simpleWorkbook() throws IOException {
        OutputStream os = new FileOutputStream("/tmp/test2.xlsx");
        Workbook wb = new Workbook(os, "MyApplication", "1.0");
        Worksheet ws = wb.newWorksheet("Sheet 1");
        ws.value(0, 0, "This is a string in A1");
        ws.finish();
        wb.finish();
        os.close();
    }
}

If I try to open it in LibreOffice Calc, I get the message:

The file 'test2.xlsx' is corrupt and therefore cannot be opened. LibreOffice can try to repair the file.

If I choose "Yes", LibreOffice is unsuccessfully with the repair.

Am I missing something?

The version of LibreOffice is:

Version: 5.1.6.2
Build ID: 1:5.1.6~rc2-0ubuntu1~xenial7

sorting problem with generated file

Hi,
When generated big file with fastexcel writer ( ~20K rows ), sorting A-Z or Z-A for some column on generated file excel crash and sometimes office closes.
It seams something makes heavy of generated file.

Date format issue

Hi ,
I am trying to set custom date format using format method of style , it is changing actual date value to some other date with format required. how to fix this issue ?

public static void main(String[] args) {

	try( OutputStream os = new FileOutputStream("C:\\TESTOUTS\\testxls_"+(new Date().getTime())+".xlsx"))
	{
		Workbook   wb = new Workbook(os, "my workbook", "1.0"); 
	    Worksheet ws = wb.newWorksheet("test");
	    ws.style(2, 3).format("MMMM dd, yyyy").set();
	    ws.value(2, 3, new  SimpleDateFormat("dd/MMM/YYYY").parse("18/Apr/2020"));
	    wb.finish();
	     // Excepted output is : April 18, 2020
                // Output return is : December 29 2020

		
		
	} catch (FileNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
	catch (Exception e) {
		e.printStackTrace();
	}

Is there any possibility bring image in fast-excel?

Hi,
We are using fast-excel more often in our project. It is working faster than other plugin.
But we can't include logo in excel cell.
Will you bring this feature in future or no idea about it?

Thanks

getCellAsBoolean always returns true

I think there is an issue with the getCellAsBoolean method of the Row.java class.

If a boolean value is set in the cell (TRUE or FALSE), the value retrieved by the library is always true.

Error while Reading excel file

I am Trying to read excel file but I am stuck at the

ReadableWorkbook wb = new ReadableWorkbook(Objects.requireNonNull(inputStream)

Following is Simple app to read data from excel file.

          public void getit(View view) throws IOException {
    File inputFile = new File("/storage/emulated/0/police/test.xlsx");
    inputFile.setReadable(true);
    if(inputFile.canRead())
        Toast.makeText(this,"it can read",Toast.LENGTH_SHORT).show();
    InputStream inputStream = null;
    try {
        inputStream = new FileInputStream(inputFile);
        Log.d(String.valueOf(this), "happen");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
   
    try ( ReadableWorkbook wb = new ReadableWorkbook(Objects.requireNonNull(inputStream))) {

        Sheet sheet = wb.getFirstSheet();
        try(Stream<Row> rows = sheet.openStream()){
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                rows.forEach(r->{
                    BigDecimal num = r.getCellAsNumber(0).orElse(null);
                    String str = r.getCellAsString(1).orElse(null);
                    Log.i(String.valueOf(this),"cell 1 = "+num+"cell 2 = "+str+"\n");
                } );
            }

        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}`

And my build.gradle file is
apply plugin: 'com.android.application'

                  android {
compileSdkVersion 29
buildToolsVersion "29.0.0"
defaultConfig {
    applicationId "android.example.com.myapplication"
    minSdkVersion 20
    targetSdkVersion 29
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
}
compileOptions {
    sourceCompatibility = '1.8'
    targetCompatibility = '1.8'
}

}

            dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation 'org.dhatim:fastexcel-reader:0.10.2'

}

I am getting the following error

    Process: android.example.com.myapplication, PID: 30869
java.lang.IllegalStateException: Could not execute method for android:onClick
    at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:390)
    at android.view.View.performClick(View.java:5619)
    at android.view.View$PerformClick.run(View.java:22298)
    at android.os.Handler.handleCallback(Handler.java:754)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:165)
    at android.app.ActivityThread.main(ActivityThread.java:6375)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:912)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:802)
 Caused by: java.lang.reflect.InvocationTargetException
    at java.lang.reflect.Method.invoke(Native Method)
    at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
    at android.view.View.performClick(View.java:5619) 
    at android.view.View$PerformClick.run(View.java:22298) 
    at android.os.Handler.handleCallback(Handler.java:754) 
    at android.os.Handler.dispatchMessage(Handler.java:95) 
    at android.os.Looper.loop(Looper.java:165) 
    at android.app.ActivityThread.main(ActivityThread.java:6375) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:912) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:802) 
 Caused by: java.lang.NoSuchMethodError: No virtual method toPath()Ljava/nio/file/Path; in class Ljava/io/File; or its super classes (declaration of 'java.io.File' appears in /system/framework/core-oj.jar)
    at org.apache.commons.compress.archivers.zip.ZipFile.<init>(ZipFile.java:218)
    at org.apache.commons.compress.archivers.zip.ZipFile.<init>(ZipFile.java:201)
    at org.apache.commons.compress.archivers.zip.ZipFile.<init>(ZipFile.java:162)
    at org.apache.poi.openxml4j.util.ZipSecureFile.<init>(ZipSecureFile.java:122)
    at org.apache.poi.openxml4j.opc.internal.ZipHelper.openZipFile(ZipHelper.java:205)
    at org.apache.poi.openxml4j.opc.ZipPackage.<init>(ZipPackage.java:140)
    at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:271)
    at org.dhatim.fastexcel.reader.ReadableWorkbook.open(ReadableWorkbook.java:192)
    at org.dhatim.fastexcel.reader.ReadableWorkbook.<init>(ReadableWorkbook.java:52)
    at android.example.com.myapplication.MainActivity.getit(MainActivity.java:46)
    at java.lang.reflect.Method.invoke(Native Method) 
    at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385) 
    at android.view.View.performClick(View.java:5619) 
    at android.view.View$PerformClick.run(View.java:22298) 
    at android.os.Handler.handleCallback(Handler.java:754) 
    at android.os.Handler.dispatchMessage(Handler.java:95) 
    at android.os.Looper.loop(Looper.java:165) 
    at android.app.ActivityThread.main(ActivityThread.java:6375) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:912) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:802) 

How to wrap text within cell.

Hi.

When I am generating the Excel. Mentioned text shows in single line within a cell. Below image for your reference.

single_line

But I want text like below image within a cell.
wrap text

Thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.