NOPI使用方式
注意事项:读取数据时要判断celltype
创建指定格式的excel时要 先把所需要的font创建好,cellstyle创建好,然后创建格子,给各个格子设定风格
假设所有格子内容都是字符串,第一行为数据列,下面则是datatable与excel互转的方法
public static DataTable ExcelToTable(string fileName)
{
ISheet sheet = null;
IWorkbook workbook = null;
DataTable table = new DataTable();
using (FileStream fs = File.OpenRead(fileName))
{
if (fileName.Contains(".xlsx"))
{
workbook = new XSSFWorkbook(fs);
}
else if (fileName.Contains(".xls"))
{
workbook = new HSSFWorkbook(fs);
}
else
{
throw new Exception("不是有效的Excel类型");
}
}
sheet = workbook.GetSheetAt(0);
IRow firstRow = sheet.GetRow(0);
int cellCount = firstRow.LastCellNum;//列的总数
for (int i = 0; i < cellCount; i++)
{
ICell cell = firstRow.GetCell(i);
if (cell != null)
{
string cellValue = cell.StringCellValue;
DataColumn column = new DataColumn(cellValue);
table.Columns.Add(column);
}
}
int rowCount = sheet.LastRowNum;
for (int i = 1; i < rowCount; i++)
{
IRow row = sheet.GetRow(i);
if (row == null)
continue;
DataRow dataRow = table.NewRow();
for (int j = 0; j < cellCount; j++)
{
string value = row.GetCell(j) == null ? "" : row.GetCell(j).ToString();
dataRow[j] = value;
}
table.Rows.Add(dataRow);
}
return table;
}
/// <summary>
/// 表中内容均为string
/// </summary>
public static void ExportToXls(string fileName, DataTable dataTable)
{
HSSFWorkbook workBook = new HSSFWorkbook();
ISheet sheet = workBook.CreateSheet();
int i = 1;
int jL = dataTable.Columns.Count;
IRow r0 = sheet.CreateRow(0);//列头
int jj = 0;
foreach (DataColumn item in dataTable.Columns)
{
ICell cell = r0.CreateCell(jj);
cell.CellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
cell.SetCellValue(item.ColumnName);
jj++;
}
foreach (DataRow item in dataTable.Rows)
{
IRow row = sheet.CreateRow(i);
for (int j = 0; j < jL; j++)
{
ICell cell = row.CreateCell(j);
cell.SetCellValue(item[j].ToString());
}
i++;
}
using (FileStream fs = File.OpenWrite(fileName))
{
workBook.Write(fs);
}
}
public static void DataGridViewToExcel(DataGridView dgv, string defaultName = "")
{
#region
string fileNameString = defaultName;
if (string.IsNullOrEmpty(fileNameString))
{
SaveFileDialog dlg = new SaveFileDialog();
dlg.FileName = defaultName;
dlg.DefaultExt = "xls";
dlg.Filter = "Excel 2003 文件(*.xls)|*.xls|Excel 2007 文件(*.xlsx)|*.xlsx";
if (dlg.ShowDialog() == DialogResult.Cancel) return;
fileNameString = dlg.FileName;
}
if (string.IsNullOrEmpty(fileNameString)) return;
string ext = ".xls";
if (fileNameString.ToLower().EndsWith(".xlsx")) ext = ".xlsx";
int rowscount = dgv.Rows.Count;
int colscount = dgv.Columns.Count;
if (rowscount <= 0)
{
MessageBox.Show("没有数据可供保存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
if (colscount <= 0)
{
MessageBox.Show("没有数据可供保存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
if (ext.ToLower() == ".xls" && rowscount > 65536)
{
MessageBox.Show("数据记录数太多(最多不能超过65536条),不能保存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
if (ext.ToLower() == ".xlsx" && rowscount > 1048576)
{
MessageBox.Show("数据记录数太多(最多不能超过1048576条),不能保存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
if ((ext.ToLower() == ".xls" && colscount > 255) || (ext.ToLower() == ".xlsx" && colscount > 16384))
{
MessageBox.Show("数据记录行数太多,不能保存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
FileInfo file = new FileInfo(fileNameString);
if (file.Exists)
{
try
{
file.Delete();
}
catch (Exception error)
{
MessageBox.Show(error.Message, "删除失败 ", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
}
#endregion
IWorkbook objWorkbook = null;
ISheet objsheet = null;
try
{
if (ext.ToLower() == ".xls")
{
objWorkbook = new HSSFWorkbook();
}
else
{
objWorkbook = new XSSFWorkbook();
}
objsheet = objWorkbook.CreateSheet("sheet1");
IRow rowHeader = objsheet.CreateRow(0);
ICellStyle style = objWorkbook.CreateCellStyle();
style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
int displayColumnsCount = 0;
for (int i = 0; i <= dgv.ColumnCount - 1; i++)
{
if (dgv.Columns[i].Visible == true)
{
rowHeader.CreateCell(displayColumnsCount).SetCellValue(dgv.Columns[i].HeaderText.Trim());
ICell cellHeader = rowHeader.GetCell(displayColumnsCount);
cellHeader.CellStyle = style;
objsheet.SetColumnWidth(displayColumnsCount, 20 * 256); //设置列宽
displayColumnsCount++;
}
}
displayColumnsCount = 1;
int idx = 1;
for (int row = 0; row < rowscount; row++)
{
if (dgv.Rows[row].Cells[0].FormattedValue.ToString() != "")
{
try
{
IRow newRow = objsheet.CreateRow(idx);
int colIndex = 0; //真实的列
for (int col = 0; col < colscount; col++)
{
if (dgv.Columns[col].Visible == false)
continue;
ICell cell = newRow.CreateCell(colIndex);
++colIndex;
cell.CellStyle = style;
//cell.SetCellValue(dgv.Rows[row].Cells[col].FormattedValue);
switch (dgv.Columns[col].ValueType.Name)
{
case "Boolean":
cell.SetCellValue((bool)dgv.Rows[row].Cells[col].FormattedValue);
break;
case "Double":
if (dgv.Rows[row].Cells[col].FormattedValue.ToString() == "-")
{
cell.SetCellValue(dgv.Rows[row].Cells[col].FormattedValue.ToString());
}
else if (string.IsNullOrEmpty(dgv.Rows[row].Cells[col].FormattedValue.ToString()))
{
cell.SetCellValue("-");
}
else
{
cell.SetCellValue(double.Parse(dgv.Rows[row].Cells[col].FormattedValue.ToString()));
}
break;
case "DateTime":
//cell.SetCellValue(DateTime.Parse(dgv.Rows[row].Cells[col].FormattedValue.ToString()));
if (dgv.Rows[row].Cells[col].FormattedValue.ToString() == "-")
{
cell.SetCellValue(dgv.Rows[row].Cells[col].FormattedValue.ToString());
}
else if (string.IsNullOrEmpty(dgv.Rows[row].Cells[col].FormattedValue.ToString()))
{
cell.SetCellValue("-");
}
else
{
cell.SetCellValue(dgv.Rows[row].Cells[col].FormattedValue.ToString());
}
break;
case "String":
if (dgv.Rows[row].Cells[col].FormattedValue.ToString() == "-")
{
cell.SetCellValue(dgv.Rows[row].Cells[col].FormattedValue.ToString());
}
else if (string.IsNullOrEmpty(dgv.Rows[row].Cells[col].FormattedValue.ToString()))
{
cell.SetCellValue("-");
}
else
{
cell.SetCellValue(dgv.Rows[row].Cells[col].FormattedValue.ToString());
}
break;
default:
cell.SetCellValue(dgv.Rows[row].Cells[col].FormattedValue.ToString());
break;
}
}
++idx;
}
catch (Exception error1)
{
MessageBox.Show(error1.Message, "警告 ", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
}
}
using (FileStream stream = new FileStream(fileNameString, FileMode.Create, FileAccess.ReadWrite))
{
objWorkbook.Write(stream);
}
}
catch (Exception error)
{
MessageBox.Show(error.Message, "警告 ", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
finally
{
objsheet = null;
objWorkbook = null;
}
if (string.IsNullOrEmpty(defaultName))
{
if (MessageBox.Show("数据成功导出到\"" + fileNameString + "\",是否现在打开?", "导出",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
System.Diagnostics.Process.Start(fileNameString);
}
}
}
如果要操作excel,最好写个excelHelper类进行处理
public static void ExportDataGeneral(DataTable data, string defaultName = "")
{
#region 通用处理
string fileNameString = defaultName;
if (string.IsNullOrEmpty(fileNameString))
{
SaveFileDialog dlg = new SaveFileDialog();
dlg.FileName = defaultName;
dlg.DefaultExt = "xls";
dlg.Filter = "Excel 2003 文件(*.xls)|*.xls|Excel 2007 文件(*.xlsx)|*.xlsx";
if (dlg.ShowDialog() == DialogResult.Cancel) return;
fileNameString = dlg.FileName;
}
if (string.IsNullOrEmpty(fileNameString)) return;
string ext = ".xls";
if (fileNameString.ToLower().EndsWith(".xlsx")) ext = ".xlsx";
int rowscount = data.Rows.Count;
int colscount = data.Columns.Count;
if (rowscount <= 0)
{
MessageBox.Show("没有数据可供保存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
if (colscount <= 0)
{
MessageBox.Show("没有数据可供保存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
if (ext.ToLower() == ".xls" && rowscount > 65536)
{
MessageBox.Show("数据记录数太多(最多不能超过65536条),不能保存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
if (ext.ToLower() == ".xlsx" && rowscount > 1048576)
{
MessageBox.Show("数据记录数太多(最多不能超过1048576条),不能保存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
if ((ext.ToLower() == ".xls" && colscount > 255) || (ext.ToLower() == ".xlsx" && colscount > 16384))
{
MessageBox.Show("数据记录行数太多,不能保存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
FileInfo file = new FileInfo(fileNameString);
if (file.Exists)
{
try
{
file.Delete();
}
catch (Exception error)
{
MessageBox.Show(error.Message, "删除失败 ", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
}
#endregion
IWorkbook objWorkbook = null;
ISheet objsheet = null;
try
{
if (ext.ToLower() == ".xls")
{
objWorkbook = new HSSFWorkbook();
}
else
{
objWorkbook = new XSSFWorkbook();
}
objsheet = objWorkbook.CreateSheet("用户数据");
ICellStyle style = objWorkbook.CreateCellStyle();
style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
#region 数据头
IRow rowHeader = objsheet.CreateRow(0);
int displayColumnsCount = 0;
for (int i = 0; i < data.Columns.Count; i++)
{
string caption = data.Columns[i].Caption.Trim();
if (data.Columns[i].ExtendedProperties.ContainsKey("DisplayName"))
{
caption = data.Columns[i].ExtendedProperties["DisplayName"].ToString();
}
rowHeader.CreateCell(displayColumnsCount).SetCellValue(caption);
ICell cellHeader = rowHeader.GetCell(displayColumnsCount);
cellHeader.CellStyle = style;
objsheet.SetColumnWidth(displayColumnsCount, 20 * 256);
displayColumnsCount++;
}
#endregion
#region 定义格式
Dictionary<string, ICellStyle> dicStyles = new Dictionary<string, ICellStyle>();
IDataFormat format = objWorkbook.CreateDataFormat();
ICellStyle cellStyle = objWorkbook.CreateCellStyle();
cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Right;
cellStyle.DataFormat = format.GetFormat("0.00");
dicStyles.Add("0.00", cellStyle);
ICellStyle cellStyle1 = objWorkbook.CreateCellStyle();
cellStyle1.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Right;
cellStyle1.DataFormat = format.GetFormat("0");
dicStyles.Add("0", cellStyle1);
//自定义0.000
ICellStyle cellStyle2 = objWorkbook.CreateCellStyle();
cellStyle2.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Right;
cellStyle2.DataFormat = format.GetFormat("0.000");
dicStyles.Add("0.000", cellStyle);
//常规
ICellStyle cellStyle3 = objWorkbook.CreateCellStyle();
cellStyle3.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Right;
cellStyle3.DataFormat = format.GetFormat("General");
dicStyles.Add("General", cellStyle3);
//文本
ICellStyle styleG = objWorkbook.CreateCellStyle();
styleG.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;
styleG.DataFormat = format.GetFormat("@");
dicStyles.Add("@", styleG);
//文本
ICellStyle styleDate = objWorkbook.CreateCellStyle();
styleDate.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;
styleDate.DataFormat = format.GetFormat("yyyy-mm-dd");
dicStyles.Add("yyyy-mm-dd", styleDate);
#endregion
#region 数据处理
for (int row = 0; row < data.Rows.Count; row++)
{
IRow contentRow = objsheet.CreateRow(row + 1);
int idx = 0;
for (int col = 0; col < data.Columns.Count; col++)
{
//填充数据
if (!(data.Rows[row][col] is DBNull) && !string.IsNullOrEmpty(data.Rows[row][col].ToString()))
{
Type type = data.Columns[col].DataType;
if (type == typeof(DateTime))
{
contentRow.CreateCell(idx).SetCellValue((DateTime)data.Rows[row][col]);
}
else if (type == typeof(double))
{
double tmp = 0;
if (double.TryParse(data.Rows[row][col].ToString(), out tmp))
{
contentRow.CreateCell(idx).SetCellValue(tmp);
}
}
else if (type == typeof(string))
{
contentRow.CreateCell(idx).SetCellValue(data.Rows[row][col].ToString());
}
else if (type == typeof(bool))
{
bool tmp = false;
if (bool.TryParse(data.Rows[row][col].ToString(), out tmp))
{
contentRow.CreateCell(idx).SetCellValue(tmp ? "是" : "否");
}
}
else
{
contentRow.CreateCell(idx).SetCellValue(data.Rows[row][col].ToString());
}
//设置格式
if (data.Columns[col].ExtendedProperties.ContainsKey("DisplayFormat"))
{
string displayFormat = data.Columns[col].ExtendedProperties["DisplayFormat"].ToString();
if (!string.IsNullOrEmpty(displayFormat))
{
string key = displayFormat;
if (displayFormat.ToUpper().StartsWith("N"))
{
displayFormat = displayFormat.Substring(1);
key = "0";
if (int.Parse(displayFormat) > 0)
{
key += ".";
for (int i = 0; i < int.Parse(displayFormat); i++)
{
key += "0";
}
}
}
if (dicStyles.ContainsKey(key))
{
contentRow.GetCell(idx).CellStyle = dicStyles[key];
}
else
{
ICellStyle styleCustom = objWorkbook.CreateCellStyle();
styleCustom.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;
styleCustom.DataFormat = format.GetFormat(key);
dicStyles.Add(key, styleCustom);
contentRow.GetCell(idx).CellStyle = styleCustom;
}
}
else
{
if (type == typeof(DateTime))
{
contentRow.GetCell(idx).CellStyle = styleDate;
}
else if (type == typeof(double))
{
contentRow.GetCell(idx).CellStyle = cellStyle;
}
else if (type == typeof(string))
{
contentRow.GetCell(idx).CellStyle = styleG;
}
else
{
contentRow.GetCell(idx).CellStyle = cellStyle3;
}
}
}
}
++idx;
}
}
#endregion
using (FileStream stream = new FileStream(fileNameString, FileMode.Create, FileAccess.ReadWrite))
{
objWorkbook.Write(stream);
}
}
catch (Exception error)
{
}
finally
{
objsheet = null;
objWorkbook = null;
}
if (string.IsNullOrEmpty(defaultName))
{
if (MessageBox.Show("数据成功导出到\"" + fileNameString + "\",是否现在打开?", "导出",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
System.Diagnostics.Process.Start(fileNameString);
}
}
}
public static List<T> ExcelToList<T>(string fileName) where T:new()
{
Type tp = typeof(T);
List<T> retval = new List<T>();
List<string> cols = new List<string>();
IWorkbook objWorkbook = null;
ISheet objsheet = null;
List<PropertyInfo> infos = tp.GetProperties().ToList();
try
{
using (FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite))
{
string ext = ".xls";
if (fileName.ToLower().EndsWith(".xlsx")) ext = ".xlsx";
if (ext.ToLower() == ".xls")
{
objWorkbook = new HSSFWorkbook(stream);
}
else
{
objWorkbook = new XSSFWorkbook(stream);
}
}
objsheet = objWorkbook.GetSheetAt(0);
int rowCount = objsheet.PhysicalNumberOfRows;
int colsCount = objsheet.GetRow(0).PhysicalNumberOfCells;
for (int i = 0; i < colsCount; i++)
{
string colName = objsheet.GetRow(0).GetCell(i).StringCellValue.Trim();
cols.Add(colName);
}
for (int row = 1; row < rowCount; row++)
{
IRow hr = objsheet.GetRow(row);
if (hr == null) continue;
T t = new T();
for (int i = 0; i < colsCount; i++)
{
var pInfo = infos.Find(p => p.Name == cols[i]);
if (pInfo != null)
{
pInfo.SetValue(t, getValue(hr, i).ToString(),null);
}
}
retval.Add(t);
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
objsheet = null;
objWorkbook = null;
}
return retval;
}
public static DataTable ExcelToDatable(string fileName)
{
DataTable dt = new DataTable();
IWorkbook objWorkbook = null;
ISheet objsheet = null;
try
{
using (FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite))
{
string ext = ".xls";
if (fileName.ToLower().EndsWith(".xlsx")) ext = ".xlsx";
if (ext.ToLower() == ".xls")
{
objWorkbook = new HSSFWorkbook(stream);
}
else
{
objWorkbook = new XSSFWorkbook(stream);
}
}
objsheet = objWorkbook.GetSheetAt(0);
int rowCount = objsheet.PhysicalNumberOfRows;
int colsCount = objsheet.GetRow(0).PhysicalNumberOfCells;
for (int i = 0; i < colsCount; i++)
{
string colName = objsheet.GetRow(0).GetCell(i).StringCellValue;
dt.Columns.Add(colName);
}
DataRow dr;
for (int row = 1; row < rowCount; row++)
{
IRow hr = objsheet.GetRow(row);
if (hr == null) continue;
dr = dt.NewRow();
for (int i = 0; i < colsCount; i++)
{
dr[i] = getValue(hr, i);
}
dt.Rows.Add(dr);
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
objsheet = null;
objWorkbook = null;
}
return dt;
}
static object getValue(IRow hr, int idx)
{
object val = null;
if (hr.GetCell(idx) == null || hr.GetCell(idx).ToString() == "")
{
val = DBNull.Value;
}
else
{
switch (hr.GetCell(idx).CellType)
{
case CellType.Numeric:
//if (idx == 0)
//{
// val = (object)hr.GetCell(idx).DateCellValue.ToString("yyyyMMdd");
//}
//else if (idx == 3)
//{
// val = (object)hr.GetCell(idx).NumericCellValue.ToString("P");
//}
//else
//{
// val = (object)hr.GetCell(idx).NumericCellValue;
//}
val = (object)hr.GetCell(idx).NumericCellValue;
break;
default:
//Formulate
hr.GetCell(idx).SetCellType(CellType.String);
val = (object)hr.GetCell(idx).StringCellValue;
break;
}
}
return val;
}