发布网友 发布时间:2022-04-22 08:23
共2个回答
热心网友 时间:2022-06-18 13:30
import java.io.File;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
/**
* Excel导出(你需要引入jxl的jar包)
*/
public class Test {
public static void main(String[] args)
{
Test test = new Test();
test.exportExcel();
}
/**
* 导出(导出到磁盘)
*/
public void exportExcel() {
WritableWorkbook book = null;
try {
// 打开文件
book = Workbook.createWorkbook(new File("D:/测试.xls"));
// 生成名为"学生"的工作表,参数0表示这是第一页
WritableSheet sheet = book.createSheet("学生", 0);
// 指定单元格位置是第一列第一行(0, 0)以及单元格内容为张三
Label label = new Label(0, 0, "张三");
// 将定义好的单元格添加到工作表中
sheet.addCell(label);
// 保存数字的单元格必须使用Number的完整包路径
jxl.write.Number number = new jxl.write.Number(1, 0, 30);
sheet.addCell(number);
// 写入数据并关闭文件
book.write();
} catch (Exception e) {
System.out.println(e);
}finally{
if(book!=null){
try {
book.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
热心网友 时间:2022-06-18 13:31
引用Spire.Xls.jar, Java打印Excel:
import com.spire.xls.Workbook;
import javax.print.PrintService;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
public class PrintExcel {
public static void main(String[] args) throws Exception{
//Create a workbook and load an Excel file
Workbook workbook = new Workbook();
workbook.loadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.xlsx");
//Create a PrinterJob object
PrinterJob printerJob = PrinterJob.getPrinterJob();
//Specify printer name
PrintService myPrintService = findPrintService("\\\\192.168.1.104\\HP LaserJet P1007");
printerJob.setPrintService(myPrintService);
//Create a PageFormat object and set it to the default size and orientation
PageFormat pageFormat = printerJob.defaultPage();
//Return a copy of the Paper object associated with this PageFormat.
Paper paper = pageFormat .getPaper();
//Set the imageable area of this Paper.
paper.setImageableArea(0,0,pageFormat .getWidth(),pageFormat .getHeight());
//Set the Paper object for this PageFormat.
pageFormat .setPaper(paper);
//Set the number of copies
printerJob .setCopies(1);
//Call painter to render the pages in the specified format
printerJob .setPrintable(workbook,pageFormat);
//execute print
try {
printerJob.print();
} catch (PrinterException e) {
e.printStackTrace();
}
}
//Get print service by printer name
private static PrintService findPrintService(String printerName) {
PrintService[] printServices = PrinterJob.lookupPrintServices();
for (PrintService printService : printServices) {
if (printService.getName().equals(printerName)) {
return printService;
}
}
return null;
}
}