zoukankan      html  css  js  c++  java
  • 2021年4月7日

    时间:1.5个小时左右

    代码:200行左右

    博客:1

    学习内容:自己尝试写exel表的生成

    这个是代码,可以勉强生成也还算可以了。

    
    
    package bjfu.it.sun.tem;


    import androidx.annotation.NonNull;
    import androidx.appcompat.app.AppCompatActivity;
    import androidx.core.app.ActivityCompat;
    import androidx.core.content.ContextCompat;

    import android.Manifest;
    import android.app.AlertDialog;
    import android.content.ContentValues;
    import android.content.Context;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.content.pm.PackageManager;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.os.Build;
    import android.os.Bundle;
    import android.os.Environment;
    import android.os.StrictMode;
    import android.util.Log;
    import android.view.View;

    import android.widget.Button;
    import android.widget.Toast;

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

    import bjfu.it.sun.tem.model.dao.TemperatureAccounrDao;
    import bjfu.it.sun.tem.model.dao.UserAccountDao;
    import bjfu.it.sun.tem.model.db.UserAccountDB;
    import bjfu.it.sun.tem.model.dean.Teminfo;
    import bjfu.it.sun.tem.util.SPDDataUtils;
    import jxl.Workbook;
    import jxl.WorkbookSettings;
    import jxl.format.Alignment;
    import jxl.format.Border;
    import jxl.format.BorderLineStyle;
    import jxl.format.Colour;
    import jxl.format.VerticalAlignment;
    import jxl.read.biff.BiffException;
    import jxl.write.Label;
    import jxl.write.WritableCellFormat;
    import jxl.write.WritableFont;
    import jxl.write.WritableSheet;
    import jxl.write.WritableWorkbook;
    import jxl.write.WriteException;



    public class ExportActivity extends AppCompatActivity implements View.OnClickListener {
    private Button export;
    private AlertDialog alertDialog;
    Teminfo teminfo;
    TemperatureAccounrDao temperatureAccounrDao;
    List<Teminfo>teminfos=new ArrayList<>();
    private UserAccountDao userAccountDao ;

    String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};

    private int REQUEST_PERMISSION_CODE = 1000;

    private static WritableFont arial14font = null;//可写字体
    private static WritableCellFormat arial14format = null;//单元格格式

    private static WritableFont arial10font = null;
    private static WritableCellFormat arial10format = null;

    private static WritableFont arial12font = null;
    private static WritableCellFormat arial12format = null;

    private static WritableFont song12font = null;//可写字体
    private static WritableCellFormat song12format = null;//单元格格式

    private static WritableFont kai12font = null;//可写字体
    private static WritableCellFormat kai12format = null;//单元格格式

    private final static String UTF8_ENCODING = "UTF-8";


    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_export);
    requestPermission();

    StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
    StrictMode.setVmPolicy(builder.build());
    builder.detectFileUriExposure();
    initView();

    }

    private void initView(){
    export=findViewById(R.id.export);
    export.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
    switch (v.getId()){
    case R.id.export:
    exportExcel(this);

    break;
    }
    }

    //请求权限
    private void requestPermission() {
    if (Build.VERSION.SDK_INT > 23) {
    if (ContextCompat.checkSelfPermission(ExportActivity.this, permissions[0]) == PackageManager.PERMISSION_GRANTED) {
    Log.e(getLocalClassName(),"requestPermission:" + "用户之前已经授予了权限!");
    } else {
    requestPermissions(permissions, REQUEST_PERMISSION_CODE);
    }
    }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == REQUEST_PERMISSION_CODE) {
    if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
    Log.e(getLocalClassName(),"申请成功");
    } else {
    AlertDialog.Builder builder = new AlertDialog.Builder(ExportActivity.this);
    builder.setTitle("permission");
    builder.setMessage("点击允许才可以使用");
    builder.setPositiveButton("去允许", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
    if (alertDialog != null && alertDialog.isShowing()) {
    alertDialog.dismiss();
    }
    ActivityCompat.requestPermissions(ExportActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
    }
    });
    alertDialog = builder.create();
    alertDialog.setCanceledOnTouchOutside(false);
    alertDialog.show();
    }
    }
    }
    private void showDialogTipUserRequestPermission() {
    ActivityCompat.requestPermissions(this, permissions, 321);
    }

    //单元格的格式设置 字体大小 颜色 对齐方式、背景颜色等...
    private void format() {
    try {
    //字体 黑体, 字号 14 bold 粗体
    arial14font = new WritableFont(WritableFont.createFont("黑体"), 18, WritableFont.BOLD);
    arial14font.setColour(Colour.BLACK);//字体的颜色
    // arial14font.setUnderlineStyle(UnderlineStyle.SINGLE);//设置下划线

    //初始化单元格格式
    arial14format = new WritableCellFormat(arial14font);
    arial14format.setAlignment(Alignment.CENTRE);//对齐方式
    arial14format.setBorder(Border.ALL, BorderLineStyle.THIN);//边框的格式
    // arial14format.setBackground(Colour.VERY_LIGHT_YELLOW);//底色


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

    arial12font = new WritableFont(WritableFont.ARIAL, 10);
    arial12format = new WritableCellFormat(arial12font);
    arial12format.setAlignment(Alignment.CENTRE);
    arial12format.setBorder(Border.ALL, BorderLineStyle.THIN);

    song12font = new WritableFont(WritableFont.createFont("宋体"), 12);
    song12format = new WritableCellFormat(song12font);
    song12format.setAlignment(Alignment.CENTRE);
    song12format.setBorder(Border.ALL, BorderLineStyle.THIN);

    kai12font = new WritableFont(WritableFont.createFont("楷体"), 10);
    kai12format = new WritableCellFormat(kai12font);
    kai12format.setAlignment(Alignment.CENTRE);
    kai12format.setBorder(Border.ALL, BorderLineStyle.THIN);

    } catch (WriteException e) {
    e.printStackTrace();
    }
    }
    /**
    * 初始化Excel
    * 写入字段名称,表名
    *
    * @param filePath 导出excel的存放地址
    * @param sheetName Excel表格的表名
    * @ colName excel中包含的列名
    */
    public void initExcel(File filePath, String sheetName) {
    format();
    //创建一个工作薄,就是整个Excel文档
    WritableWorkbook workbook = null;
    try {
    // File file = new File(filePath);
    if (!filePath.exists()) {
    filePath.createNewFile();
    }
    //使用Workbook创建一个工作薄,就是整个Excel文档
    workbook = Workbook.createWorkbook(filePath);
    //设置表格的名称(两个参数分别是工作表名字和插入位置,这个位置从0开始)
    WritableSheet sheet = workbook.createSheet(sheetName, 0);
    //创建label标签:实际就是单元格的标签(三个参数分别是:col + 1列,row + 1行, 内容, 单元格格式)
    // Label label = new Label(0, 0, filePath, arial14format);//设置第一行的单元格标签为:标题
    //将标签加入到工作表中
    // sheet.addCell(label);

    //通过writablesheet.mergeCells(int x,int y,int m,int n);来实现的。
    // 表示将从第x+1列,y+1行到m+1列,n+1行合并 (四个点定义了两个坐标,左上角和右下角)
    sheet.mergeCells(0, 0, 6, 0);
    sheet.addCell(new Label(0, 0, "学生14天健康情况登记表", arial14format));
    sheet.setRowView(0, 520);
    sheet.addCell(new Label(0,1,"单位名称:",song12format));
    sheet.setRowView(1, 520);
    sheet.mergeCells(1,1,3,1);
    sheet.addCell(new Label(1,1,"石家庄铁道大学",kai12format));
    sheet.addCell(new Label(4,1,"填表日期:",song12format));
    sheet.mergeCells(5,1,6,1);
    sheet.addCell(new Label(5,1,timenow(),kai12format));
    sheet.addCell(new Label(0,2,"姓名:",kai12format));
    sheet.mergeCells(1,2,3,2);
    sheet.addCell(new Label(1,2,"贾亚赛",kai12format));

    sheet.addCell(new Label(4,2,"学号:",kai12format));
    sheet.mergeCells(5,2,6,2);
    sheet.addCell(new Label(5,2,"20194058",kai12format));
    sheet.addCell(new Label(0,3,"目前健康状况:",kai12format));
    sheet.setRowView(3, 400);
    sheet.mergeCells(1,3,3,3);
    sheet.addCell(new Label(1,3,"良好"));
    sheet.addCell(new Label(4,3,"手机号:",kai12format));
    sheet.mergeCells(5,3,6,3);
    sheet.addCell(new Label(5,3,"19832586253",kai12format));
    sheet.mergeCells(0, 4, 6, 4);
    sheet.addCell(new Label(0,4,"每日体温、健康状况监测(周期14天)",arial14format));
    sheet.setRowView(4, 520);
    sheet.addCell(new Label(0,5,"日期",kai12format));
    sheet.addCell(new Label(1,5,"每日体温℃",kai12format));
    sheet.addCell(new Label(2,5,"健康状况",kai12format));
    sheet.addCell(new Label(3,5,"当日所在地",kai12format));
    sheet.mergeCells(3,5,4,5);
    sheet.addCell(new Label(5,5,"备注",kai12format));
    sheet.mergeCells(5,5,6,5);




    workbook.write();// 写入数据
    } catch (IOException | WriteException e) {
    e.printStackTrace();
    } finally {
    if (workbook != null) {
    try {
    workbook.close();// 关闭文件
    } catch (IOException | WriteException e) {
    e.printStackTrace();
    }
    }
    }
    }


    //导出
    private void exportExcel(Context context) {
    String path = getExternalFilesDir("exter_test").getPath();
    String fileName00 = "test.txt";
    File file = new File(path+"/"+"xxxxxxx");
    try {
    if (!file.exists()) {
    boolean mkdir = file.mkdir();//创建文件夹

    }
    }catch (Exception e){
    e.printStackTrace();
    }
    File files=new File(file.getPath()+"/"+"text.xls");
    try {
    if(!files.exists()) {
    boolean newFile = files.createNewFile();//创建文件
    }
    } catch (IOException e) {
    e.printStackTrace();
    }
    // String[] title = {"姓名", "年龄", "男孩","分数"};
    String sheetName = "表格名称";
    initExcel(files,sheetName);


    Toast.makeText(context, "导出Excel成功", Toast.LENGTH_SHORT).show();
    // writeObjListToExcel(demoBeanList, files.getPath(), context);
    }

    public String timenow(){
    Calendar calendar = Calendar.getInstance();
    //年
    int year = calendar.get(Calendar.YEAR);
    //月
    int month = calendar.get(Calendar.MONTH) + 1;
    //日
    int day = calendar.get(Calendar.DAY_OF_MONTH);
    //获取系统时间
    //小时
    int hour = calendar.get(Calendar.HOUR_OF_DAY);
    //分钟
    int minute = calendar.get(Calendar.MINUTE);
    //秒
    int second = calendar.get(Calendar.SECOND);
    String tem=year + "年" + month + "月" + day + "日" + hour + ":" + minute;
    return tem;
    }
    //建立一行数据
    //x行,Y列
    public void createCell(Teminfo person, int x, WritableSheet sheet) throws WriteException {
    Label label=new Label(0,x,person.getTime());
    sheet.addCell(label);
    Label label1=new Label(1,x,person.getTemperature());
    sheet.addCell(label1);
    int t=0;
    String tem="";
    if(Float.parseFloat(person.getTemperature())>35&&Float.parseFloat(person.getTemperature())<37){
    tem="良好";
    }
    else {

    tem="患病";
    }
    Label label2=new Label(2,x,tem);
    sheet.addCell(label2);
    Label label3=new Label(3,x,person.getAddress());
    sheet.addCell(label3);
    Label label4=new Label(4,x,person.getOther());
    sheet.addCell(label4);
    }
    //从第6行开始,插入数据;
    public void insertdata(WritableSheet sheet) throws WriteException {
    int r=6;
    int t=0;

    // Log.e("tttttt",persons.size()+"");
    t = teminfos.size();//数据库表中的数据条数;
    if(t>=14){
    //从6行到20行;
    for(Teminfo teminfo:teminfos){
    if(r>19){
    break;
    }
    createCell(teminfo,r,sheet);
    r++;
    }
    }
    if(t<14){
    for(Teminfo teminfo:teminfos){
    createCell(teminfo,r,sheet);
    r++;
    }
    }

    }
    //得到手机号
    private String getPhone(){
    String str=null;
    str= SPDDataUtils.getUserinfo(this) ;
    return str;
    }

    //得到姓名
    private String getName(){
    String str;
    userAccountDao=new UserAccountDao(this) ;
    str=userAccountDao .getAccountByPhone(getPhone()).getName() ;
    return str;
    }

    //显示信息的方法
    private void showMSg(String msg){
    Toast.makeText(this,msg,Toast.LENGTH_SHORT ).show() ;
    }
    }
    
    
  • 相关阅读:
    Python爬虫学习遇到的问题
    爬取网页内容后写入文件报错UnicodeEncodeError: 'gbk' codec can't encode的问题解决方案
    第14.6节 使用Python urllib.request模拟浏览器访问网页的实现代码
    Mina源码阅读笔记(一)-整体解读
    使用异步 I/O 大大提高应用程序的性能
    同步和异步,阻塞和非阻塞
    位运算详解
    php引用传值详解
    PHP获取指定地区的天气
    新闻网站开发-手机端-基于Wordpress
  • 原文地址:https://www.cnblogs.com/j-y-s/p/14903262.html
Copyright © 2011-2022 走看看