- Saved searches
- Use saved searches to filter your results more quickly
- License
- centic9/poi-on-android
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- Читаем XLSX на Android 5 (ART) c Apache POI XSSF
- Saved searches
- Use saved searches to filter your results more quickly
- License
- SUPERCILEX/poi-android
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
A sample project that shows how Apache POI can be used in an Android application
License
centic9/poi-on-android
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
This is a sample Android application to show how Apache POI can be used on Android.
It consists of two projects:
- poishadow: A small helper project to produce a shaded jar-file for Apache POI which includes all necessary dependencies and fixes a few things that usually hinder you deploying Apache POI on Android
- poitest: A very small sample Android application which performs some actions on XLSX-, PPTX and DOCX-files using Apache POI. See MainActivity for the actual code
In order to work around problems with finding a suitable XML Parser, currently the following system properties need to be set manually during startup of your application (let me know if you know of a better way to do this, see issue #10)
System.setProperty("org.apache.poi.javax.xml.stream.XMLInputFactory", "com.fasterxml.aalto.stax.InputFactoryImpl"); System.setProperty("org.apache.poi.javax.xml.stream.XMLOutputFactory", "com.fasterxml.aalto.stax.OutputFactoryImpl"); System.setProperty("org.apache.poi.javax.xml.stream.XMLEventFactory", "com.fasterxml.aalto.stax.EventFactoryImpl");
Supported Android versions
The sample project uses minimum SDK version 26, which maps to Android 8.0. Higher versions should work as well, older ones are likely not supported any more.
Note: Some dependencies of Apache POI are not included in the shading to keep it’s size at bay. If you use code areas which require commons-codec, commons-collections4 or any of the other dependencies, you may need to add them in your Android application in addition to the poishadow-all.jar file dependency.
Unfortunately Android does not provide any of the classes in package java.awt and thus any code which uses code from there will not work. This affects various places in Apache POI, e.g. when handling column-width, images or other graphical operations.
A few classes have been re-implemented in the src-folder in project poishadow . If you are missing some you might be able to add re-implementations there.
If you want to get started quickly, there is a ready-made jar-file available in the release section.
You should be able to simply add this to your Android project and use the Apache POI classes from it.
If you would like to change how the jar-file is built, e.g. if you need classes that are excluded, use a different version of POI or would like to adjust the build in some other way, you can build the shaded jar with the following steps:
You will need the following pieces in order to get started
- A recent Java SDK, preferably Java 8
- An installation of the Android SDK, either the one included with Android Studio or a separate download, see https://developer.android.com/studio/index.html#downloads
git clone https://github.com/centic9/poi-on-android.git cd poi-on-android
Configure where your Android SDK resides:
echo "sdk.dir=/opt/android-sdk-linux" > local.properties
Configure the version of the Android Build Tools that you have installed.
Then build the shadow-jar, for some reason this works better if executed separately:
Finally run the build and some testing. Make sure you have a device connected, e.g. the Android emulator.
./gradlew build connectedCheck
For only the jar-files run just build
If you find this tool useful and would like to support it, you can Sponsor the author
Start an Android emulator
/platform-tools/adb install ./poitest/build/outputs/apk/poitest-debug.apk
- You can use the resulting jar-file poishadow/build/libs/poishadow-all.jar in your own project, the code in directory poitest is just a small sample Android application to show that it works.
- This was only tested in Android Studio with the Android emulator until now, should work on real Android as well, though!
- Tested with targetSdkVersion 26 and minSdkVersion 26
- Add more actual functionality to the sample application, currently it just performs some basic functionality on documents.
- Some parts of the JDK are missing on Android, e.g. AWT-related classes. Some of these are missing when some functionality of Apache POI is used and thus currently crash the sample project. There are some libraries which provide these classes, but none was in a state that allowed it to easily integrate it here.
Copyright 2015-2022 Dominik Stadler
Licensed under the Apache License, Version 2.0 (the «License»); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an «AS IS» BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
About
A sample project that shows how Apache POI can be used in an Android application
Читаем XLSX на Android 5 (ART) c Apache POI XSSF
Некоторое время назад я писал, как при помощи языческих танцев и прочих паранормальных активностей я добился работы Apache POI XSSF на Android 4. Всё становится гораздо проще с Android Build Tools (21+) и Android 5 (ART).
Теперь достаточно собрать проект с поддержкой multi-dex и всё будет работать* на устройствах c ART. Я полагаю, что это происходит благодаря Ahead-of-time (AOT) compilation на устройстве и multi-dex, теперь, как таковой, нужен только как промежуточный этап.
* К сожалению не всё так гладко. В зависимостях проекта есть xmlbeans-2.6.0.jar, который запакован с ошибкой и содержит дубликаты классов. Это приводит к провалу сборки на задаче packageAllDebugClassesForMultiDex, со следующей ошибкой:
Error:Execution failed for task ':app:packageAllDebugClassesForMultiDex'. > java.util.zip.ZipException: duplicate entry: org/apache/xmlbeans/xml/stream/Location.class
XMLBeans придётся перепаковать.
Этот дефект уже сто лет в обед как зарегистрирован issues.apache.org/jira/browse/XMLBEANS-499, однако воз и ныне там.
Для полноценной работы нам понадобятся следующие JAR файлы:
poi-3.12-20150511.jar
poi-ooxml-3.12-20150511.jar
poi-ooxml-schemas-3.12-20150511.jar
stax-1.2.0.jar
stax-api-1.0.1.jar
xmlbeans-2.6.0.jar — из-за этого файла не получится беззаботно добавить POI в зависимости проекта
Все вышеуказанные файлы доступны в загрузках POI archive.apache.org/dist/poi/release/bin
- добавить com.android.support:multidex в зависимости проекта.
- Включить multiDex в defaultConfig
- для задачи com.android.build.gradle.tasks.Dex добавить параметр —core-library, чтобы избежать ошибок из за классов с namespace javax.
Если использовать gradle, то получим конфиг примерно следующего содержания:
apply plugin: 'com.android.application' android < compileSdkVersion 22 buildToolsVersion "22.0.1" defaultConfig < // . другие стандартные настройки . minSdkVersion 21 targetSdkVersion 21 multiDexEnabled true >buildTypes < release < minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' >> //исключим текстовые файлы: packagingOptions < exclude 'META-INF/DEPENDENCIES' exclude 'META-INF/NOTICE' exclude 'META-INF/NOTICE.txt' exclude 'META-INF/LICENSE' exclude 'META-INF/LICENSE.txt' >project.tasks.withType(com.android.build.gradle.tasks.Dex) < additionalParameters=['--core-library'] //javax namespace fix >> dependencies < // . остальные зависимости проекта . compile 'com.android.support:multidex:1.0.1' >
Всё! Теперь мы имеем, предположительно, полностью функциональный POI на Android, который, опять таки, предположительно, может читать и все остальные openxml форматы, поскольку нам не пришлось обрезать содержимое jarов, как это было сделано в прошлый раз. Прошу любиить, экспериментировать и делиться результатами.
При желании можно также озадачиться тем, чтобы сделать javax->aavax хак, но в этот раз я счёл это лишним.
Если очень хочется, чтобы зависимости вытягивались сами, то можно написать рутину для multidex.JarMergingTask, которая бы перепаковывала jar xmlbeans, и я даже написал такую рутину. Однако, после этого билд стал валиться на preDex из-за javax в stax-api. Мне не удалось найти быстрого способа добавить —core-library в preDex и на этом у меня кончилось терпение. Наиболее разумным мне кажется просто добавить все необходимые jarы, вместе с перепакованным xmlbeans в libs проекта.
В качестве заключения:
Я сделал два jara содержащих всё необходимое и не содержащие дубликатов в xmlbeans, файлы можно скачать в этом репозитории:
github.com/andruhon/android5xlsx пользуйте на здовровье, но на свой страх и риск.
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
SUPERCILEX / poi-android Public archive
License
SUPERCILEX/poi-android
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
POIA is a simple library enabling Apache POI usage on Android.
Add JitPack to your repositories :
allprojects < repositories < // . maven < url 'https://jitpack.io' > > >
And the POIA dependency itself:
implementation "com.github.SUPERCILEX.poi-android:poi:$poiVersion"
If you’re using proguard, also add:
implementation "com.github.SUPERCILEX.poi-android:proguard:$poiVersion"
If you want source code and documentation, add the real Apache POI dependency as compileOnly :
compileOnly "org.apache.poi:poi-ooxml:$poiVersion"
If you need a newer version of Apache POI than is provided by this transpiler, updating is as simple as making a fork and changing a few lines of code:
val workbook = if (isUnsupportedDevice) < showToast(getString(R.string.export_unsupported_device_rationale)) HSSFWorkbook() > else < XSSFWorkbook() > // Example unsupportedDevice property val isUnsupportedDevice by lazy < VERSION.SDK_INT VERSION_CODES.LOLLIPOP || isLowRamDevice >
Make sure to test your implementation thoroughly pre-L since HSSFWorkbook only supports a subset of the Workbook ‘s APIs and might throw a UOE. Wikipedia even goes so far as to call it the «Horrible SpreadSheet Format» so consider yourself warned. 😁