using System;
using System.IO;
using NPOI.HSSF;
using NPOI.HPSF;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
//導出常用方法示例(使用該方法時需先引入NPOI.dll文件):
class Program{
public static void Main(string[] args){
ExportExcel();
}
/// <summary>
/// 導出基本操作示例方法
/// </summary>
public static void ExportExcel(){
//初始化一個新的HSSFWorkbook實例
HSSFWorkbook hssfworkbook = new HSSFWorkbook();
//設置excel必須的文件屬性(該屬性用來存儲 如作者、標題、標記、備注、主題等信息,右鍵可查看的屬性信息)
DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
dsi.Company = "NPOI Team";
SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
si.Subject = "NPOI SDK Example";
hssfworkbook.DocumentSummaryInformation = dsi;
hssfworkbook.SummaryInformation = si;
//新建一個Workbook默認都會新建3個Sheet(標准的Excel文件有3個Sheet)。所以必須加入下面的創建Sheet的代碼才能保證生成的文件正常
HSSFSheet sheet = (HSSFSheet)hssfworkbook.CreateSheet("new sheet");
// hssfworkbook.CreateSheet("Sheet1");
// hssfworkbook.CreateSheet("Sheet2");
// hssfworkbook.CreateSheet("Sheet3");
//建創行
IRow row1=sheet.CreateRow(0);
//建單元格,比如創建A1位置的單元格:
row1.CreateCell(0).SetCellValue(1);
//簡寫 shee1.CreateRow(0).CreateCell(0).SetCellValue("This is a Sample");
//把C3:E5合並為一個單元格 並賦值
ICell cell= sheet.CreateRow(2).CreateCell(2);
cell.SetCellValue("This is a Sample");
sheet.AddMergedRegion(new NPOI.SS.Util.Region(2, 2, 4, 4));
//設置樣式 居中 字體
ICellStyle style = hssfworkbook.CreateCellStyle();
style.VerticalAlignment = VerticalAlignment.Center;
style.Alignment = HorizontalAlignment.Center;
IFont font = hssfworkbook.CreateFont();
font.FontHeight = 20 * 20;
style.SetFont(font);
cell.CellStyle = style;
//把這個HSSFWorkbook實例寫入文件
FileStream file = new FileStream("Example1.xls", FileMode.Create);
hssfworkbook.Write(file);
file.Close();
}
public static string now(){
return DateTime.Now.ToString("HH:mm:ss.fff");
}
}
本文轉自開源博客,鏈接:https://my.oschina.net/u/1242247/blog/2990403,原創:devcang
