1、前言:
最近公司项目都用上了数据库,都要求具有报表的功能,需要导出Execl文件,或则使用Execl表导入相关的数据。于是查看资料发现很多都是使用微软提供的office COM组件,于是尝试了下,发现在一台电脑调试好了,然后在别的电脑上有容易出问题,后来总结出问题,发现是由于不同电脑安装的office 版本存在差异,所有,容易引起异常。
后来,在学习JAVA web的时候,发现在java web 中存在非常好用的一个开源项目POI,其实现脱离office 不同版本之间的差异性,后来百度查阅相关资料后发现,在C# 中也存在对应的NPOI。于是,记录下。
2、POI 和 NPOI
Apache POI是Apache软件基金会的开源项目,POI提供API给Java程序对Microsoft Office格式档案读和写的功能。 .NET的开发人员则可以利用NPOI (POI for .NET) 来存取 Microsoft Office文档的功能。
private void LoadingThread()
{
lock (mLockObject)
{
mIsLoading = true;
}
DataTable dt = ExcelToDataTable("LoostCardUID", true);
if (dt == null)
{
return;
}
ShowRecord(dt);
WriteLogcat("导入数据完成 ...", 0);
lock (mLockObject)
{
mIsLoading = false;
}
}
private string fileName = null; //文件名
private IWorkbook workbook = null;
private FileStream fs = null;
///
/// 将excel中的数据导入到DataTable中
///
/// excel工作薄sheet的名称
/// 第一行是否是DataTable的列名
/// 返回的DataTable
public DataTable ExcelToDataTable(string sheetName, bool isFirstRowColumn)
{
ISheet sheet = null;
DataTable data = new DataTable();
int startRow = 0;
try
{
fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
if (fileName.IndexOf(".xlsx") > 0) // 2007版本
workbook = new XSSFWorkbook(fs);
else if (fileName.IndexOf(".xls") > 0) // 2003版本
workbook = new HSSFWorkbook(fs);
if (sheetName != null)
{
sheet = workbook.GetSheet(sheetName);
if (sheet == null) //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet
{
//sheet = workbook.GetSheetAt(0);
MessageBox.Show("未找到正确的Execl表格文件!");
return null;
}
}
else
{
sheet = workbook.GetSheetAt(0);
}
if (sheet != null)
{
IRow firstRow = sheet.GetRow(0);
int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数
if (isFirstRowColumn)
{
for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
ICell cell = firstRow.GetCell(i);
if (cell != null)
{
cell.SetCellType(CellType.String);
string cellValue = cell.StringCellValue;
if (cellValue != null)
{
DataColumn column = new DataColumn(cellValue);
data.Columns.Add(column);
}
}
}
startRow = sheet.FirstRowNum + 1;
}
else
{
startRow = sheet.FirstRowNum;
}
//最后一列的标号
int rowCount = sheet.LastRowNum;
for (int i = startRow; i <= rowCount; ++i)
{
IRow row = sheet.GetRow(i);
if (row == null) continue; //没有数据的行默认是null
DataRow dataRow = data.NewRow();
for (int j = row.FirstCellNum; j < cellCount; ++j)
{
if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null
{
row.GetCell(j).SetCellType(CellType.String);
dataRow[j] = row.GetCell(j).ToString();
}
}
data.Rows.Add(dataRow);
}
}
return data;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return null;
}
}
///
/// Datable导出成Excel
///
///
/// 导出路径(包括文件名与扩展名)
public void TableToExcel(DataTable dt, string file, int type)
{
HSSFWorkbook workbook;
string fileExt = Path.GetExtension(file).ToLower();
if (fileExt == ".xls")
{
workbook = new HSSFWorkbook();
}
else
{
workbook = null;
}
if (workbook == null)
{
return;
}
ISheet sheet = workbook.CreateSheet("激活卡发卡记录");
ICellStyle style = workbook.CreateCellStyle();
ICellStyle dataStyle = workbook.CreateCellStyle();
ICellStyle dataStyle2 = workbook.CreateCellStyle();
HSSFPalette palette = workbook.GetCustomPalette(); //调色板实例
palette.SetColorAtIndex(8, 200, 235, 253);
palette.SetColorAtIndex(9, 255, 250, 239);
palette.SetColorAtIndex(10, 236, 249, 255);
HSSFColor hssFColorTitle = palette.FindColor(200, 235, 253);
HSSFColor hssFColorData = palette.FindColor(255, 250, 239);
HSSFColor hssFColorData2 = palette.FindColor(236, 249, 255);
style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
style.WrapText = true;
style.FillForegroundColor = hssFColorTitle.Indexed;
style.FillPattern = FillPattern.SolidForeground;
style.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
style.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
style.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
style.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
style.BottomBorderColor = NPOI.HSSF.Util.HSSFColor.Grey25Percent.Index;
style.LeftBorderColor = NPOI.HSSF.Util.HSSFColor.Grey25Percent.Index;
style.RightBorderColor = NPOI.HSSF.Util.HSSFColor.Grey25Percent.Index;
style.TopBorderColor = NPOI.HSSF.Util.HSSFColor.Grey25Percent.Index;
dataStyle.WrapText = true;
dataStyle.FillForegroundColor = hssFColorData.Indexed;
dataStyle.FillPattern = FillPattern.SolidForeground;
dataStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
dataStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
dataStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
dataStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
dataStyle.BottomBorderColor = NPOI.HSSF.Util.HSSFColor.Grey25Percent.Index;
dataStyle.LeftBorderColor = NPOI.HSSF.Util.HSSFColor.Grey25Percent.Index;
dataStyle.RightBorderColor = NPOI.HSSF.Util.HSSFColor.Grey25Percent.Index;
dataStyle.TopBorderColor = NPOI.HSSF.Util.HSSFColor.Grey25Percent.Index;
dataStyle2.WrapText = true;
dataStyle2.FillForegroundColor = hssFColorData2.Indexed;
dataStyle2.FillPattern = FillPattern.SolidForeground;
dataStyle2.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
dataStyle2.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
dataStyle2.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
dataStyle2.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
dataStyle2.BottomBorderColor = NPOI.HSSF.Util.HSSFColor.Grey25Percent.Index;
dataStyle2.LeftBorderColor = NPOI.HSSF.Util.HSSFColor.Grey25Percent.Index;
dataStyle2.RightBorderColor = NPOI.HSSF.Util.HSSFColor.Grey25Percent.Index;
dataStyle2.TopBorderColor = NPOI.HSSF.Util.HSSFColor.Grey25Percent.Index;
IFont font = workbook.CreateFont();
IFont dataFont = workbook.CreateFont();
font.FontHeightInPoints = 10;
//font.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
font.FontName = "微软雅黑";
dataFont.FontHeightInPoints = 9;
dataFont.FontName = "微软雅黑";
style.SetFont(font); //HEAD样式
dataStyle.SetFont(dataFont); //数据样式
dataStyle2.SetFont(dataFont); //数据样式
//表头
IRow row = sheet.CreateRow(0); //创建第一行,表头
ICell cell = row.CreateCell(0); //写列
cell.SetCellValue("序号");
cell.CellStyle = style;
sheet.SetColumnWidth(0, 10 * 256);
cell = row.CreateCell(1); //写列
cell.SetCellValue("公司名");
cell.CellStyle = style;
sheet.SetColumnWidth(1, 40 * 256);
cell = row.CreateCell(2); //写列
cell.SetCellValue("注册码");
cell.CellStyle = style;
sheet.SetColumnWidth(2, 50 * 256);
cell = row.CreateCell(3); //写列
cell.SetCellValue("激活码");
cell.CellStyle = style;
sheet.SetColumnWidth(3, 50 * 256);
cell = row.CreateCell(4); //写列
cell.SetCellValue("有效期");
cell.CellStyle = style;
sheet.SetColumnWidth(4, 25 * 256);
cell = row.CreateCell(5); //写列
cell.SetCellValue("时间");
cell.CellStyle = style;
sheet.SetColumnWidth(5, 25 * 256);
//数据
if (type == 1)
{
//导出所有
if (dt != null && dt.Rows.Count != 0)
{
for (int ik = 0; ik < dt.Rows.Count; ik++)
{
IRow row1 = sheet.CreateRow(ik + 1); //创建第二行
cell = row1.CreateCell(0); //写列
cell.SetCellValue((ik + 1).ToString());
cell.CellStyle = dataStyle;
sheet.SetColumnWidth(0, 10 * 256);
cell = row1.CreateCell(1); //写列
cell.SetCellValue(dt.Rows[ik][1].ToString());
cell.CellStyle = dataStyle2;
sheet.SetColumnWidth(1, 40 * 256);
cell = row1.CreateCell(2); //写列
cell.SetCellValue(dt.Rows[ik][2].ToString());
cell.CellStyle = dataStyle;
sheet.SetColumnWidth(2, 50 * 256);
cell = row1.CreateCell(3); //写列
cell.SetCellValue(dt.Rows[ik][3].ToString());
cell.CellStyle = dataStyle2;
sheet.SetColumnWidth(3, 50 * 256);
cell = row1.CreateCell(4); //写列
cell.SetCellValue(dt.Rows[ik][4].ToString());
cell.CellStyle = dataStyle;
sheet.SetColumnWidth(4, 25 * 256);
cell = row1.CreateCell(5); //写列
cell.SetCellValue(dt.Rows[ik][5].ToString());
cell.CellStyle = dataStyle2;
sheet.SetColumnWidth(5, 25 * 256);
}
}
}
else
{
//导出当前列表
for (int ik = 0; ik < mList.Count; ik++)
{
IRow row1 = sheet.CreateRow(ik + 1); //创建第二行
cell = row1.CreateCell(0);
cell.SetCellValue((ik + 1).ToString());
cell.CellStyle = dataStyle;
sheet.SetColumnWidth(0, 10 * 256);
cell = row1.CreateCell(1); //写列
cell.SetCellValue(mList[ik].getName());
cell.CellStyle = dataStyle2;
sheet.SetColumnWidth(1, 40 * 256);
cell = row1.CreateCell(2); //写列
cell.SetCellValue(mList[ik].getRegistercode());
cell.CellStyle = dataStyle;
sheet.SetColumnWidth(2, 50 * 256);
cell = row1.CreateCell(3); //写列
cell.SetCellValue(mList[ik].getActivecode());
cell.CellStyle = dataStyle2;
sheet.SetColumnWidth(3, 50 * 256);
cell = row1.CreateCell(4); //写列
cell.SetCellValue(mList[ik].getTime());
cell.CellStyle = dataStyle;
sheet.SetColumnWidth(4, 25 * 256);
cell = row1.CreateCell(5); //写列
cell.SetCellValue(mList[ik].getValiditytime());
cell.CellStyle = dataStyle2;
sheet.SetColumnWidth(5, 25 * 256);
}
}
try
{
//转为字节数组
MemoryStream stream = new MemoryStream();
workbook.Write(stream);
var buf = stream.ToArray();
//保存为Excel文件
using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write))
{
fs.Write(buf, 0, buf.Length);
fs.Flush();
}
}
catch (Exception e1)
{
LogcatService.WriteLogcat(e1);
ShowMessage(0, "导出Execl 文件失败");
return;
}
ShowMessage(1, "导出Execl 文件成功");
}
这里只记录使用的部分,其他的可以百度查阅相关的资料。