NPOIを使ってデータをエクスポートする例
6639 ワード
直接コードを通して、コードに詳細なコメントがあります。このものは本当に「こじれ」です。
公式サイト:http://npoi.codeplex.com/
中国語教程(旧版):http://www.cnblogs.com/tonyqus/archive/2009/04/12/1434209.html
公式サイト:http://npoi.codeplex.com/
中国語教程(旧版):http://www.cnblogs.com/tonyqus/archive/2009/04/12/1434209.html
//- Excel
HSSFWorkbook hssfworkbook = new HSSFWorkbook();
//- Sheet
var sheet = hssfworkbook.CreateSheet(" ");
//- Sheet Row
NPOI.SS.UserModel.Row row;
//- “ ”, 。
//- , , !
var patriarch = sheet.CreateDrawingPatriarch();
//- , “Excel ” , ,
//- , “ ” 。
//-
var cellFont = hssfworkbook.CreateFont();
var cellStyle = hssfworkbook.CreateCellStyle();
//- ,
cellFont.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.BOLD;
cellFont.Color = NPOI.HSSF.Util.HSSFColor.WHITE.index;
//- FillForegroundColor , , , “ ”?
//- , FillBackgroundColor 。 。
cellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.GREY_40_PERCENT.index;
//- , 、 。 , :SOLID_FOREGROUND
cellStyle.FillPattern = NPOI.SS.UserModel.FillPatternType.SOLID_FOREGROUND;
//- , , !
cellStyle.SetFont(cellFont);
for(int i = 0 ; i <= gridView1.RowCount ; i++)
{//- GridControl GridView,i <= gridView1.RowCount
row = sheet.CreateRow(i);
foreach(GridColumn column in gridView1.Columns)
{
//-
if(column.Visible)
{
//- row cell
NPOI.SS.UserModel.Cell cell = row.CreateCell(column.VisibleIndex);
//-
if(i == 0)
{
row.HeightInPoints = 50f; //- row.Height 20
cell.SetCellValue(column.Caption); ; //-
cell.CellStyle = cellStyle; //-
}
else
{
row.HeightInPoints = 100f; // row.Height 20
object value = gridView1.GetRowCellValue(i - 1, column);
//-
if(value != null && value.GetType() == typeof(byte[]))
{
sheet.SetColumnWidth(column.VisibleIndex, 50 * 256);//- , 256
//- Excel,
var pictureIdx = hssfworkbook.AddPicture((byte[])value, NPOI.SS.UserModel.PictureType.JPEG);
//-
var anchor = new HSSFClientAnchor(
0, 0, //- ,
0, 0, //- ,
column.VisibleIndex, i,
column.VisibleIndex + 1, i + 1);
//- :
//- 5(E) 2
//- 4 : 1 ( )
//- ( ) ( 、 )
patriarch.CreatePicture(anchor, pictureIdx);//-
}
else
{
cell.SetCellValue(value.ToStringOrEmpty());
}
}
//-
cell.CellStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.CENTER;
cell.CellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.CENTER;
//-
cell.CellStyle.BorderBottom = NPOI.SS.UserModel.CellBorderType.THIN;
cell.CellStyle.BorderLeft = NPOI.SS.UserModel.CellBorderType.THIN;
cell.CellStyle.BorderRight = NPOI.SS.UserModel.CellBorderType.THIN;
cell.CellStyle.BorderTop = NPOI.SS.UserModel.CellBorderType.THIN;
cell.CellStyle.BottomBorderColor = NPOI.HSSF.Util.HSSFColor.BLACK.index;
cell.CellStyle.LeftBorderColor = NPOI.HSSF.Util.HSSFColor.BLACK.index;
cell.CellStyle.RightBorderColor = NPOI.HSSF.Util.HSSFColor.BLACK.index;
cell.CellStyle.TopBorderColor = NPOI.HSSF.Util.HSSFColor.BLACK.index;
}
}
}
FileStream file = new FileStream(fileName, FileMode.Create);
hssfworkbook.Write(file);//-
file.Close();