一添加依赖
minSdk= 26
dependencies {
implementation 'org. apache. poi: poi: 4.1 .2 '
implementation 'org. apache. poi: poi- ooxml: 4.1 .2 '
implementation 'javax. xml. stream: stax- api: 1.0 - 2 '
}
二创建方法
word">private word">void createExcelFile ( String Path ) {
Workbook workbook = word">new XSSFWorkbook ( ) ;
Sheet sheet = workbook. createSheet ( "姓名" ) ;
ArrayList < Map < Integer , Object > > arrayList = word">new ArrayList < > ( ) ;
Map < Integer , Object > m = word">new HashMap < > ( ) ;
m. put ( 0 , "物料ID" ) ;
m. put ( 1 , "物料编码" ) ;
m. put ( 2 , "名称" ) ;
m. put ( 3 , "编号" ) ;
m. put ( 4 , "规格" ) ;
m. put ( 5 , "单位" ) ;
m. put ( 6 , "单价" ) ;
m. put ( 7 , "数量" ) ;
m. put ( 8 , "厂家" ) ;
m. put ( 9 , "类别" ) ;
arrayList. add ( m) ;
word">for ( word">int i = 0 ; i < 10 ; i++ ) {
Map < Integer , Object > map = word">new HashMap < > ( ) ;
map. put ( 0 , "materialID" ) ;
map. put ( 1 , "materialEncoding" ) ;
map. put ( 2 , "materialName" ) ;
map. put ( 3 , "materialModel" ) ;
map. put ( 4 , "materialSize" ) ;
map. put ( 5 , "unit" ) ;
map. put ( 6 , "price" ) ;
map. put ( 7 , "count" ) ;
map. put ( 8 , "manufacturers" ) ;
map. put ( 9 , "type" ) ;
arrayList. add ( map) ;
}
Cell cell;
word">int size = arrayList. get ( 0 ) . size ( ) ;
word">for ( word">int i = 0 ; i < arrayList. size ( ) ; i++ ) {
Row row = sheet. createRow ( i) ;
Map < Integer , Object > map1 = arrayList. get ( i) ;
word">for ( word">int j = 0 ; j < size; j++ ) {
cell = row. createCell ( j) ;
cell. setCellValue ( ( String ) map1. get ( j) ) ;
}
}
word">try {
File file = word">new File ( Path , "example.xlsx" ) ;
FileOutputStream outputStream = word">new FileOutputStream ( file) ;
workbook. write ( outputStream) ;
outputStream. close ( ) ;
Toast . makeText ( word">this , "Excel文件已创建" , Toast . LENGTH_SHORT ) . show ( ) ;
} word">catch ( IOException e) {
e. printStackTrace ( ) ;
}
}