体温上报APP2.1

1、今日进度表:

2、今日目标:

完成第二阶段的生成导出excel表格

3、今日完成:

1、导入class.xls包

2、建立excel工具类ExcelUtil,定义要导出表格的样式

package com.example.reporttemperature;

//Excel工具类
import android.content.Context;
import android.widget.Toast;


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.format.Colour;
import jxl.write.Label;
import jxl.write.WritableCell;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

public class ExcelUtil {
    public static WritableFont arial14font = null;

    public static WritableCellFormat arial14format = null;
    public static WritableFont arial10font = null;
    public static WritableCellFormat arial10format = null;
    public static WritableFont arial12font = null;
    public static WritableCellFormat arial12format = null;

    public final static String UTF8_ENCODING = "UTF-8";
    public final static String GBK_ENCODING = "GBK";


    /**
     * 单元格的格式设置 字体大小 颜色 对齐方式、背景颜色等...
     */
    public static void format() {
        try {

            arial14font = new WritableFont(WritableFont.ARIAL, 14, WritableFont.BOLD);
            arial14font.setColour(jxl.format.Colour.LIGHT_BLUE);
            arial14format = new WritableCellFormat(arial14font);
            arial14format.setAlignment(jxl.format.Alignment.CENTRE);
            arial14format.setBorder(jxl.format.Border.ALL,jxl.format.BorderLineStyle.THIN);
            arial14format.setBackground(jxl.format.Colour.VERY_LIGHT_YELLOW);

            arial10font = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD);
            arial10format = new WritableCellFormat(arial10font);
            arial10format.setAlignment(jxl.format.Alignment.CENTRE);
            arial10format.setBorder(jxl.format.Border.ALL,jxl.format.BorderLineStyle.THIN);
            arial10format.setBackground(Colour.GRAY_25);

            arial12font = new WritableFont(WritableFont.ARIAL, 10);
            arial12format = new WritableCellFormat(arial12font);
            arial10format.setAlignment(jxl.format.Alignment.CENTRE);//对齐格式
            arial12format.setBorder(jxl.format.Border.ALL,jxl.format.BorderLineStyle.THIN); //设置边框

        } catch (WriteException e) {
            e.printStackTrace();
        }
    }



    /**
     * 初始化Excel
     * @param fileName

     */
    public static void initExcel(String fileName) {
        //format();
        WritableWorkbook workbook = null;
        try {
            File file = new File(fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
            workbook = Workbook.createWorkbook(file);
            WritableSheet sheet = workbook.createSheet("sheet1", 0);

            sheet.setRowView(3, 300); // 设置行的高度
            sheet.setRowView(20,340); //设置行高

            workbook.write();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @SuppressWarnings("unchecked")
    public static <T> void writeObjListToExcel(List<T> objList,String fileName, Context c,
                                               String classroom,String name,String ID_Number,String phone ) {
        if (objList != null && objList.size() > 0) {
            WritableWorkbook writebook = null;
            InputStream in = null;
            try {
                WorkbookSettings setEncode = new WorkbookSettings();
                setEncode.setEncoding(UTF8_ENCODING);
                in = new FileInputStream(new File(fileName));
                Workbook workbook = Workbook.getWorkbook(in);
                writebook = Workbook.createWorkbook(new File(fileName),workbook);
                WritableSheet sheet = writebook.getSheet(0);
                sheet.addCell(new Label(1,1,classroom));
                sheet.addCell(new Label(1,2,name));
                sheet.addCell(new Label(5,2,ID_Number));
                sheet.addCell(new Label(1,3,"健康"));
                sheet.addCell(new Label(5,3,phone));
                //创建单元格的标签
                Label label=new Label(0,0,"学生14天健康情况登记表");
                //将标签插入到单元格中
                sheet.addCell(label);
                sheet.addCell(new Label(0,1,"单位名称:"));
                sheet.addCell(new Label(4,1,"填表日期:"));
                sheet.addCell(new Label(0,2,"姓名:"));
                sheet.addCell(new Label(4,2,"学号:"));
                sheet.addCell(new Label(0,3,"目前健康情况:"));
                sheet.addCell(new Label(4,3,"手机号:"));
                sheet.addCell(new Label(0,4,"每日体温、健康状况检测(周期14天)"));
                sheet.addCell(new Label(0,5,"日期"));
                sheet.addCell(new Label(1,5,"每日体温"));
                sheet.addCell(new Label(2,5,"健康情况"));
                sheet.addCell(new Label(3,5,"当日所在地"));
                sheet.addCell(new Label(5,5,"备注"));
                sheet.addCell(new Label(0,20,"本人承诺:自觉履行疫情防控责任和义务,保证以上填报信息全部属实,如有隐瞒,自愿承担相应法律后果。"));
                sheet.addCell(new Label(0,21,"本人签字"));
                sheet.addCell(new Label(4,21,"签字日期"));

                for (int j = 0; j < objList.size(); j++) {

                    ArrayList<String> list = (ArrayList<String>) objList.get(j);
                    for (int i = 0; i < list.size(); i++) {
                        sheet.addCell(new Label(i,j+6, list.get(i)));

                    }
                    sheet.setRowView(j+6,350); //设置行高

                }

                sheet.mergeCells(0, 21, 1, 21); // 合并单元格-本人签字
                sheet.mergeCells(0, 20, 6, 20); // 合并单元格-承诺
                sheet.mergeCells(1, 1, 3, 1); // 合并单元格-单位名称
                sheet.mergeCells(5, 1, 6, 1); // 合并单元格-填表日期
                sheet.mergeCells(0, 4, 6, 4); // 合并单元格
                sheet.mergeCells(1, 2, 3, 2); // 合并单元格-姓名
                sheet.mergeCells(5, 2, 6, 2); // 合并单元格-学号
                sheet.mergeCells(0, 0, 6, 0); // 合并单元格
                sheet.mergeCells(5, 3, 6, 3); // 合并单元格-手机号
                sheet.mergeCells(1, 3, 3, 3); // 合并单元格-健康情况
                sheet.mergeCells(2, 21, 3, 21); // 合并单元格-本人签字
                sheet.mergeCells(5, 21, 6, 21); // 合并单元格-签字日期
                sheet.mergeCells(5, 5, 6, 5); // 合并单元格-备注
                sheet.mergeCells(3, 5, 4, 5); // 合并单元格-当日所在地
                for(int t=6;t<20;t++){
                    sheet.mergeCells(3, t, 4, t); // 合并单元格-所在地
                }
                for(int t=6;t<20;t++){
                    sheet.mergeCells(5, t, 6, t); // 合并单元格-备注
                }
                writebook.write();

                Toast.makeText(c, "Excel导出成功", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (writebook != null) {
                    try {
                        writebook.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        }
    }
}

 3、建立实体类Situation 用于存储体温上报中的信息,用以导出到excel 表格中

package com.example.reporttemperature;



public class Situation {
    private String health;
    private String date;
    private String address;
    private String temperature;


    public String getHealth() {
        return health;
    }

    public void setHealth(String health) {
        this.health = health;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getTemperature() {
        return temperature;
    }

    public void setTemperature(String temperature) {
        this.temperature = temperature;
    }



    public Situation(){

    }

    public Situation(String date,String temperature,String address,String health){

        this.temperature = temperature;
        this.address = address;
        this.date = date;
        this.health = health;


    }

}

5、CreateActivity用于生成excel表格,并将数据放入

package com.example.reporttemperature;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;


import android.widget.EditText;

import java.io.File;
import java.util.ArrayList;
import java.util.List;


public class CreateActivity extends AppCompatActivity {

    private ArrayList<ArrayList<String>> recordList;
    private List<Situation> students;
    private File file;
    private String fileName;
    private EditText ed,et ;
    private String ID_number;
    private MyOpenHelper helper=new MyOpenHelper(this);
    private String[] r;
    private String s;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create);

        Intent intent=getIntent();
        ID_number=intent.getStringExtra("IDnumber");

        r=get_phone(ID_number);
       String [][] tem=get_tem(r[0]);

        //模拟数据集合
        students = new ArrayList<>();
        for (int i = 0; i<14; i++) {
            students.add(new Situation(tem[i][0],tem[i][2],tem[i][1],"健康"));
        }
        //导出excel表
        exportExcel();
        ed=findViewById(R.id.path);
        ed.setText("Excel表格已导出至:"+getSDPath(this));
        et=findViewById(R.id.m);
        //et.setText(s+"");


    }

    /**
     * 导出excel
     */
   public void exportExcel() {

        file = new File(getSDPath(this) + "/Record2");
        makeDir(file);
        ExcelUtil.initExcel(file.toString() + "/14天健康登记表.xlsx");
        fileName = getSDPath(this) + "/Record2/14天健康登记表.xlsx";
        ExcelUtil.writeObjListToExcel(getRecordData(), fileName, this,r[2],r[0],ID_number,r[1]);
    }

    /**
     * 将数据集合 转化成ArrayList<ArrayList<String>>
     * @return
     */
    private  ArrayList<ArrayList<String>> getRecordData() {
        recordList = new ArrayList<>();
        for (int i = 0; i <students.size(); i++) {
            Situation student = students.get(i);
            ArrayList<String> beanList = new ArrayList<String>();
            beanList.add(student.getDate());
            beanList.add(student.getTemperature());
            beanList.add(student.getHealth());
            beanList.add(student.getAddress());
            recordList.add(beanList);
        }
        return recordList;
    }

    //获取sd卡地址
    public static String getSDPath(Context context) {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);// 判断sd卡是否存在

        if (sdCardExist) {
            if (Build.VERSION.SDK_INT>=29){
               //Android10之后
                sdDir = context.getExternalFilesDir(null);
            }else {
                sdDir = Environment.getExternalStorageDirectory();// 获取SD卡根目录

            }
        } else {
            sdDir = Environment.getRootDirectory();// 获取跟目录
        }
        return sdDir.toString();
    }


    public  void makeDir(File dir) {
        if (!dir.getParentFile().exists()) {
            makeDir(dir.getParentFile());
        }
        dir.mkdir();
    }

    //按照学号查找手机号
    private String[] get_phone(String text1){
        String newName="",newPhone="",newClass="";
        String []result=new String[3];
        SQLiteDatabase db=helper.getReadableDatabase();
        Cursor cursor = db.rawQuery("select * from user where idNumber = ? ", new String[]{text1});

        while (cursor.moveToNext()) {
            newName = cursor.getString(cursor.getColumnIndex("name"));
            newPhone = cursor.getString(cursor.getColumnIndex("phone"));
            newClass = cursor.getString(cursor.getColumnIndex("class"));
        }
        cursor.close();
        db.close();
        result[0]=newName;
        result[1]=newPhone;
        result[2]=newClass;

        return result;

    }

//获取体温数据库中信息
    public String[][] get_tem(String text2) {

        String[][] stringArr2=new String[100][3];
        SQLiteDatabase db = helper.getReadableDatabase();
        int i = 0;
        Cursor cursor = db.rawQuery("select * from temperature where name = ? ", new String[]{text2});

        while (cursor.moveToNext()) {

            String newDate = cursor.getString(cursor.getColumnIndex("date"));
            String newAddress = cursor.getString(cursor.getColumnIndex("address"));
            String newTemperature= cursor.getString(cursor.getColumnIndex("temperature"));

            stringArr2[i][0]=newDate;
            stringArr2[i][1]=newAddress;
            stringArr2[i][2]=newTemperature;
            ++i;

        }

       // s=stringArr2[5][2];
        cursor.close();
        db.close();

        return stringArr2;


    }



}

activity_create.xml表示导出结果

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/cata"
    tools:context=".CreateActivity">

    <EditText
        android:id="@+id/path"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="99dp"
        android:layout_marginLeft="99dp"
        android:layout_marginTop="303dp"
        android:layout_marginEnd="99dp"
        android:layout_marginRight="99dp"
        android:layout_marginBottom="383dp"
        android:ems="10"
        android:inputType="textPersonName"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/m"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="75dp"
        android:ems="10"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/path" />

</androidx.constraintlayout.widget.ConstraintLayout>
原文地址:https://www.cnblogs.com/Lizhichengweidashen/p/14899471.html