使用NPOI 2.1.1读取EXCEL2003/2007返回DataTable
winform中打开excel的筛选器设置为:openFileDialog.Filter = "Excel 文件(*.xls)|*.xls;*.xlsx";
一,不借助插件读取Excel2003、2007:
string strConn = "Provider=Microsoft.Ace.OleDb.12.0;" + "Data Source=" + path + ";" + "Extended Properties='Excel 12.0; HDR=Yes; IMEX=1'";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
string strExcel = "";
OleDbDataAdapter myCommand = null;
DataSet ds = null;
strExcel = "select * from [sheet1$]";
myCommand = new OleDbDataAdapter(strExcel, strConn);
ds = new DataSet();
myCommand.Fill(ds, "table1");
return ds;
二,使用NPOI 2.1.1读取EXCEL2003/2007
在使用NPOI 2.0.1读取Excel2007文档时,标准的日期格式2014/12/4 给读成了04-十二月-2014,不知道是我的人品差,还是版本bug,又不想手动去转换格式,试了下最新版本,解决了这问题。
调用方法就一句话:DataTable dt1 = ExcelNpoiHelper.ImportExcelAllToDt(file);
附ExcelNpoiHelper类。
using NPOI.HSSF.UserModel;
using NPOI.SS.Formula.Eval;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.UserModel;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using System.Text.RegularExpressions; namespace UploadValuationReport.excelhelper
{
public class ExcelNpoiHelper
{
#region 从datatable中将数据导出到excel
/// <summary>
/// DataTable导出到Excel的MemoryStream
/// </summary>
/// <param name="dtSource">源DataTable</param>
/// <param name="strHeaderText">表头文本</param>
static MemoryStream ExportDt(DataTable dtSource, string strHeaderText)
{
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.CreateSheet() as HSSFSheet; #region 右击文件 属性信息 //{
// DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
// dsi.Company = "NPOI";
// workbook.DocumentSummaryInformation = dsi; // SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
// si.Author = "文件作者信息"; //填加xls文件作者信息
// si.ApplicationName = "创建程序信息"; //填加xls文件创建程序信息
// si.LastAuthor = "最后保存者信息"; //填加xls文件最后保存者信息
// si.Comments = "作者信息"; //填加xls文件作者信息
// si.Title = "标题信息"; //填加xls文件标题信息
// si.Subject = "主题信息"; //填加文件主题信息
// si.CreateDateTime = DateTime.Now;
// workbook.SummaryInformation = si;
//} #endregion HSSFCellStyle dateStyle = workbook.CreateCellStyle() as HSSFCellStyle;
HSSFDataFormat format = workbook.CreateDataFormat() as HSSFDataFormat;
dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd"); //取得列宽
int[] arrColWidth = new int[dtSource.Columns.Count];
foreach (DataColumn item in dtSource.Columns)
{
arrColWidth[item.Ordinal] = Encoding.GetEncoding().GetBytes(item.ColumnName.ToString()).Length;
}
for (int i = ; i < dtSource.Rows.Count; i++)
{
for (int j = ; j < dtSource.Columns.Count; j++)
{
int intTemp = Encoding.GetEncoding().GetBytes(dtSource.Rows[i][j].ToString()).Length;
if (intTemp > arrColWidth[j])
{
arrColWidth[j] = intTemp;
}
}
}
int rowIndex = ; foreach (DataRow row in dtSource.Rows)
{
#region 新建表,填充表头,填充列头,样式 if (rowIndex == || rowIndex == )
{
if (rowIndex != )
{
sheet = workbook.CreateSheet() as HSSFSheet;
} #region 表头及样式 {
HSSFRow headerRow = sheet.CreateRow() as HSSFRow;
headerRow.HeightInPoints = ;
headerRow.CreateCell().SetCellValue(strHeaderText); HSSFCellStyle headStyle = workbook.CreateCellStyle() as HSSFCellStyle;
headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
HSSFFont font = workbook.CreateFont() as HSSFFont;
font.FontHeightInPoints = ;
font.Boldweight = ;
headStyle.SetFont(font); headerRow.GetCell().CellStyle = headStyle; sheet.AddMergedRegion(new Region(, , , dtSource.Columns.Count - ));
//headerRow.Dispose();
} #endregion #region 列头及样式 {
HSSFRow headerRow = sheet.CreateRow() as HSSFRow; HSSFCellStyle headStyle = workbook.CreateCellStyle() as HSSFCellStyle;
headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
HSSFFont font = workbook.CreateFont() as HSSFFont;
font.FontHeightInPoints = ;
font.Boldweight = ;
headStyle.SetFont(font); foreach (DataColumn column in dtSource.Columns)
{
headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
headerRow.GetCell(column.Ordinal).CellStyle = headStyle; //设置列宽
sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + ) * ); }
//headerRow.Dispose();
} #endregion rowIndex = ;
} #endregion #region 填充内容 HSSFRow dataRow = sheet.CreateRow(rowIndex) as HSSFRow;
foreach (DataColumn column in dtSource.Columns)
{
HSSFCell newCell = dataRow.CreateCell(column.Ordinal) as HSSFCell; string drValue = row[column].ToString(); switch (column.DataType.ToString())
{
case "System.String": //字符串类型
double result;
if (IsNumeric(drValue, out result))
{ double.TryParse(drValue, out result);
newCell.SetCellValue(result);
break;
}
else
{
newCell.SetCellValue(drValue);
break;
} case "System.DateTime": //日期类型
DateTime dateV;
DateTime.TryParse(drValue, out dateV);
newCell.SetCellValue(dateV); newCell.CellStyle = dateStyle; //格式化显示
break;
case "System.Boolean": //布尔型
bool boolV = false;
bool.TryParse(drValue, out boolV);
newCell.SetCellValue(boolV);
break;
case "System.Int16": //整型
case "System.Int32":
case "System.Int64":
case "System.Byte":
int intV = ;
int.TryParse(drValue, out intV);
newCell.SetCellValue(intV);
break;
case "System.Decimal": //浮点型
case "System.Double":
double doubV = ;
double.TryParse(drValue, out doubV);
newCell.SetCellValue(doubV);
break;
case "System.DBNull": //空值处理
newCell.SetCellValue("");
break;
default:
newCell.SetCellValue("");
break;
} } #endregion rowIndex++;
}
using (MemoryStream ms = new MemoryStream())
{
workbook.Write(ms);
ms.Flush();
ms.Position = ; //sheet;
//workbook.Dispose(); return ms;
}
} /// <summary>
/// DataTable导出到Excel文件
/// </summary>
/// <param name="dtSource">源DataTable</param>
/// <param name="strHeaderText">表头文本</param>
/// <param name="strFileName">保存位置</param>
public static void ExportDTtoExcel(DataTable dtSource, string strHeaderText, string strFileName)
{
using (MemoryStream ms = ExportDt(dtSource, strHeaderText))
{
using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write))
{
byte[] data = ms.ToArray();
fs.Write(data, , data.Length);
fs.Flush();
}
}
}
#endregion #region 从excel2003/2007中将数据导出到datatable(默认第一行为标头,实际数据从第二行读取)
/// <summary>
/// 自动辨别excel2003/2007
/// </summary>
/// <param name="strFileName">excel文档路径</param>
/// <returns></returns>
public static DataTable ImportExcelAllToDt(string strFileName)
{
DataTable dt = new DataTable();
IWorkbook workbook;
using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
{
workbook = WorkbookFactory.Create(file);//使用接口,自动识别excel2003/2007格式
}
ISheet sheet = workbook.GetSheetAt();//得到里面第一个sheet
//HSSFSheet sheet = hssfworkbook.GetSheetAt(0) as HSSFSheet;
if (Path.GetExtension(strFileName).Equals(".xlsx"))
{
dt = ImportExcel2007InDt(sheet, , true);
return dt;
}
else
{
dt = ImportExcel2003InDt(sheet, , true);
return dt;
} } /// <summary>读取excel
/// 默认第一行为标头,实际数据从第二行读取
/// </summary>
/// <param name="strFileName">excel文档路径</param>
/// <returns></returns>
public static DataTable ImportExcel2003ToDt(string strFileName)
{
DataTable dt = new DataTable();
IWorkbook hssfworkbook;
using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
{
hssfworkbook = new HSSFWorkbook(file);
}
HSSFSheet sheet = hssfworkbook.GetSheetAt() as HSSFSheet;
dt = ImportExcel2003InDt(sheet, , true);
return dt;
} /// <summary>读取excel
/// 默认第一行为标头,实际数据从第二行读取
/// </summary>
/// <param name="strFileName">excel文档路径</param>
/// <returns></returns>
public static DataTable ImportExcel2007ToDt(string strFileName)
{
DataTable dt = new DataTable();
IWorkbook hssfworkbook;
using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
{
hssfworkbook = new XSSFWorkbook(file);
}
ISheet sheet = hssfworkbook.GetSheetAt();
dt = ImportExcel2007InDt(sheet, , true);
return dt;
} /// <summary>
/// 读取excel
/// </summary>
/// <param name="strFileName">excel文件路径</param>
/// <param name="sheetName">需要导出的sheet</param>
/// <param name="headerRowIndex">列头所在行号,-1表示没有列头</param>
/// <returns></returns>
public static DataTable ImportExcel2003ToDt(string strFileName, string sheetName, int headerRowIndex)
{
IWorkbook workbook;
using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
{
workbook = new HSSFWorkbook(file);
}
HSSFSheet sheet = workbook.GetSheet(sheetName) as HSSFSheet;
DataTable table = new DataTable();
table = ImportExcel2003InDt(sheet, headerRowIndex, true);
//ExcelFileStream.Close();
workbook = null;
sheet = null;
return table;
} /// <summary>
/// 读取excel
/// </summary>
/// <param name="strFileName">excel文件路径</param>
/// <param name="sheetName">需要导出的sheet</param>
/// <param name="headerRowIndex">列头所在行号,-1表示没有列头</param>
/// <returns></returns>
public static DataTable ImportExcel2007ToDt(string strFileName, string sheetName, int headerRowIndex)
{
IWorkbook workbook;
using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
{
workbook = new XSSFWorkbook(file);
}
HSSFSheet sheet = workbook.GetSheet(sheetName) as HSSFSheet;
DataTable table = new DataTable();
table = ImportExcel2007InDt(sheet, headerRowIndex, true);
//ExcelFileStream.Close();
workbook = null;
sheet = null;
return table;
} /// <summary>
/// 读取excel
/// </summary>
/// <param name="strFileName">excel文件路径</param>
/// <param name="sheetIndex">需要导出的sheet序号</param>
/// <param name="headerRowIndex">列头所在行号,-1表示没有列头</param>
/// <returns></returns>
public static DataTable ImportExcel2003ToDt(string strFileName, int sheetIndex, int headerRowIndex)
{
HSSFWorkbook workbook;
using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
{
workbook = new HSSFWorkbook(file);
}
HSSFSheet sheet = workbook.GetSheetAt(sheetIndex) as HSSFSheet;
DataTable table = new DataTable();
table = ImportExcel2003InDt(sheet, headerRowIndex, true);
//ExcelFileStream.Close();
workbook = null;
sheet = null;
return table;
}
/// <summary>
/// 读取excel
/// </summary>
/// <param name="strFileName">excel文件路径</param>
/// <param name="sheetIndex">需要导出的sheet序号</param>
/// <param name="headerRowIndex">列头所在行号,-1表示没有列头</param>
/// <returns></returns>
public static DataTable ImportExcel2007ToDt(string strFileName, int sheetIndex, int headerRowIndex)
{
IWorkbook workbook;
using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
{
workbook = new XSSFWorkbook(file);
}
HSSFSheet sheet = workbook.GetSheetAt(sheetIndex) as HSSFSheet;
DataTable table = new DataTable();
table = ImportExcel2007InDt(sheet, headerRowIndex, true);
//ExcelFileStream.Close();
workbook = null;
sheet = null;
return table;
} /// <summary>
/// 读取excel
/// </summary>
/// <param name="strFileName">excel文件路径</param>
/// <param name="sheetName">需要导出的sheet</param>
/// <param name="headerRowIndex">列头所在行号,-1表示没有列头</param>
/// <param name="needHeader">是否需要头</param>
/// <returns></returns>
public static DataTable ImportExcel2003ToDt(string strFileName, string sheetName, int headerRowIndex, bool needHeader)
{
IWorkbook workbook;
using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
{
workbook = new HSSFWorkbook(file);
}
HSSFSheet sheet = workbook.GetSheet(sheetName) as HSSFSheet;
DataTable table = new DataTable();
table = ImportExcel2003InDt(sheet, headerRowIndex, needHeader);
//ExcelFileStream.Close();
workbook = null;
sheet = null;
return table;
} /// <summary>
/// 读取excel
/// </summary>
/// <param name="strFileName">excel文件路径</param>
/// <param name="sheetIndex">需要导出的sheet序号</param>
/// <param name="headerRowIndex">列头所在行号,-1表示没有列头</param>
/// <param name="needHeader">是否需要头</param>
/// <returns></returns>
public static DataTable ImportExcel2003ToDt(string strFileName, int sheetIndex, int headerRowIndex, bool needHeader)
{
HSSFWorkbook workbook;
using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
{
workbook = new HSSFWorkbook(file);
}
HSSFSheet sheet = workbook.GetSheetAt(sheetIndex) as HSSFSheet;
DataTable table = new DataTable();
table = ImportExcel2003InDt(sheet, headerRowIndex, needHeader);
//ExcelFileStream.Close();
workbook = null;
sheet = null;
return table;
} static DataTable ImportExcel2003InDt(ISheet sheet, int headerRowIndex, bool needHeader)
{
DataTable table = new DataTable();
HSSFRow headerRow;
int cellCount;
try
{
if (headerRowIndex < || !needHeader)
{
headerRow = sheet.GetRow() as HSSFRow;
cellCount = headerRow.LastCellNum; for (int i = headerRow.FirstCellNum; i <= cellCount; i++)
{
DataColumn column = new DataColumn(Convert.ToString(i));
table.Columns.Add(column);
}
}
else
{
headerRow = sheet.GetRow(headerRowIndex) as HSSFRow;
cellCount = headerRow.LastCellNum; for (int i = headerRow.FirstCellNum; i <= cellCount; i++)
{
if (headerRow.GetCell(i) == null)
{
if (table.Columns.IndexOf(Convert.ToString(i)) > )
{
DataColumn column = new DataColumn(Convert.ToString("重复列名" + i));
table.Columns.Add(column);
}
else
{
DataColumn column = new DataColumn(Convert.ToString(i));
table.Columns.Add(column);
} }
else if (table.Columns.IndexOf(headerRow.GetCell(i).ToString()) > )
{
DataColumn column = new DataColumn(Convert.ToString("重复列名" + i));
table.Columns.Add(column);
}
else
{
DataColumn column = new DataColumn(headerRow.GetCell(i).ToString());
table.Columns.Add(column);
}
}
}
int rowCount = sheet.LastRowNum;
for (int i = (headerRowIndex + ); i <= sheet.LastRowNum; i++)
{
try
{
HSSFRow row;
if (sheet.GetRow(i) == null)
{
row = sheet.CreateRow(i) as HSSFRow;
}
else
{
row = sheet.GetRow(i) as HSSFRow;
} DataRow dataRow = table.NewRow(); for (int j = row.FirstCellNum; j <= cellCount; j++)
{
try
{
if (row.GetCell(j) != null)
{
switch (row.GetCell(j).CellType)
{
case CellType.String:
string str = row.GetCell(j).StringCellValue;
if (str != null && str.Length > )
{
dataRow[j] = str.ToString();
}
else
{
dataRow[j] = null;
}
break;
case CellType.Numeric:
if (DateUtil.IsCellDateFormatted(row.GetCell(j)))
{
dataRow[j] = DateTime.FromOADate(row.GetCell(j).NumericCellValue);
}
else
{
dataRow[j] = Convert.ToDouble(row.GetCell(j).NumericCellValue);
}
break;
case CellType.Boolean:
dataRow[j] = Convert.ToString(row.GetCell(j).BooleanCellValue);
break;
case CellType.Error:
dataRow[j] = ErrorEval.GetText(row.GetCell(j).ErrorCellValue);
break;
case CellType.Formula:
switch (row.GetCell(j).CachedFormulaResultType)
{
case CellType.String:
string strFORMULA = row.GetCell(j).StringCellValue;
if (strFORMULA != null && strFORMULA.Length > )
{
dataRow[j] = strFORMULA.ToString();
}
else
{
dataRow[j] = null;
}
break;
case CellType.Numeric:
dataRow[j] = Convert.ToString(row.GetCell(j).NumericCellValue);
break;
case CellType.Boolean:
dataRow[j] = Convert.ToString(row.GetCell(j).BooleanCellValue);
break;
case CellType.Error:
dataRow[j] = ErrorEval.GetText(row.GetCell(j).ErrorCellValue);
break;
default:
dataRow[j] = "";
break;
}
break;
default:
dataRow[j] = "";
break;
}
}
}
catch (Exception exception)
{
//wl.WriteLogs(exception.ToString());
}
}
table.Rows.Add(dataRow);
}
catch (Exception exception)
{
//wl.WriteLogs(exception.ToString());
}
}
}
catch (Exception exception)
{
//wl.WriteLogs(exception.ToString());
}
return table;
} /// <summary>
/// 将制定sheet中的数据导出到datatable中
/// </summary>
/// <param name="sheet">需要导出的sheet</param>
/// <param name="headerRowIndex">列头所在行号,-1表示没有列头</param>
/// <param name="needHeader">是否需要列头</param>
/// <returns></returns>
static DataTable ImportExcel2007InDt(ISheet sheet, int headerRowIndex, bool needHeader)
{
DataTable table = new DataTable();
NPOI.XSSF.UserModel.XSSFRow headerRow;
int cellCount;
try
{
if (headerRowIndex < || !needHeader)
{
headerRow = sheet.GetRow() as NPOI.XSSF.UserModel.XSSFRow;
cellCount = headerRow.LastCellNum; for (int i = headerRow.FirstCellNum; i <= cellCount; i++)
{
DataColumn column = new DataColumn(Convert.ToString(i));
table.Columns.Add(column);
}
}
else
{
headerRow = sheet.GetRow(headerRowIndex) as NPOI.XSSF.UserModel.XSSFRow;
cellCount = headerRow.LastCellNum; for (int i = headerRow.FirstCellNum; i <= cellCount; i++)
{
if (headerRow.GetCell(i) == null)
{
if (table.Columns.IndexOf(Convert.ToString(i)) > )
{
DataColumn column = new DataColumn(Convert.ToString("重复列名" + i));
table.Columns.Add(column);
}
else
{
DataColumn column = new DataColumn(Convert.ToString(i));
table.Columns.Add(column);
} }
else if (table.Columns.IndexOf(headerRow.GetCell(i).ToString()) > )
{
DataColumn column = new DataColumn(Convert.ToString("重复列名" + i));
table.Columns.Add(column);
}
else
{
DataColumn column = new DataColumn(headerRow.GetCell(i).ToString());
table.Columns.Add(column);
}
}
}
int rowCount = sheet.LastRowNum;
for (int i = (headerRowIndex + ); i <= sheet.LastRowNum; i++)
{
try
{
NPOI.XSSF.UserModel.XSSFRow row;
if (sheet.GetRow(i) == null)
{
row = sheet.CreateRow(i) as NPOI.XSSF.UserModel.XSSFRow;
}
else
{
row = sheet.GetRow(i) as NPOI.XSSF.UserModel.XSSFRow;
} DataRow dataRow = table.NewRow(); for (int j = row.FirstCellNum; j <= cellCount; j++)
{
try
{
if (row.GetCell(j) != null)
{
switch (row.GetCell(j).CellType)
{
case CellType.String:
string str = row.GetCell(j).StringCellValue;
if (str != null && str.Length > )
{
dataRow[j] = str.ToString();
}
else
{
dataRow[j] = null;
}
break;
case CellType.Numeric:
if (DateUtil.IsCellDateFormatted(row.GetCell(j)))
{
dataRow[j] = DateTime.FromOADate(row.GetCell(j).NumericCellValue);
}
else
{
dataRow[j] = Convert.ToDouble(row.GetCell(j).NumericCellValue);
}
break;
case CellType.Boolean:
dataRow[j] = Convert.ToString(row.GetCell(j).BooleanCellValue);
break;
case CellType.Error:
dataRow[j] = ErrorEval.GetText(row.GetCell(j).ErrorCellValue);
break;
case CellType.Formula:
switch (row.GetCell(j).CachedFormulaResultType)
{
case CellType.String:
string strFormula = row.GetCell(j).StringCellValue;
if (!string.IsNullOrEmpty(strFormula))
{
dataRow[j] = strFormula;
}
else
{
dataRow[j] = null;
}
break;
case CellType.Numeric:
dataRow[j] = Convert.ToString(row.GetCell(j).NumericCellValue);
break;
case CellType.Boolean:
dataRow[j] = Convert.ToString(row.GetCell(j).BooleanCellValue);
break;
case CellType.Error:
dataRow[j] = ErrorEval.GetText(row.GetCell(j).ErrorCellValue);
break;
default:
dataRow[j] = "";
break;
}
break;
default:
dataRow[j] = "";
break;
}
}
}
catch (Exception exception)
{
//wl.WriteLogs(exception.ToString());
}
}
table.Rows.Add(dataRow);
}
catch (Exception exception)
{
//wl.WriteLogs(exception.ToString());
}
}
}
catch (Exception exception)
{
//wl.WriteLogs(exception.ToString());
}
return table;
}
#endregion #region 更新excel中的数据
/// <summary>
/// 更新Excel表格
/// </summary>
/// <param name="outputFile">需更新的excel表格路径</param>
/// <param name="sheetname">sheet名</param>
/// <param name="updateData">需更新的数据</param>
/// <param name="coluid">需更新的列号</param>
/// <param name="rowid">需更新的开始行号</param>
public static void UpdateExcel(string outputFile, string sheetname, string[] updateData, int coluid, int rowid)
{
FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read); HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile);
ISheet sheet1 = hssfworkbook.GetSheet(sheetname);
for (int i = ; i < updateData.Length; i++)
{
try
{
if (sheet1.GetRow(i + rowid) == null)
{
sheet1.CreateRow(i + rowid);
}
if (sheet1.GetRow(i + rowid).GetCell(coluid) == null)
{
sheet1.GetRow(i + rowid).CreateCell(coluid);
} sheet1.GetRow(i + rowid).GetCell(coluid).SetCellValue(updateData[i]);
}
catch (Exception ex)
{
// wl.WriteLogs(ex.ToString());
throw;
}
}
try
{
readfile.Close();
FileStream writefile = new FileStream(outputFile, FileMode.Create, FileAccess.Write);
hssfworkbook.Write(writefile);
writefile.Close();
}
catch (Exception ex)
{
// wl.WriteLogs(ex.ToString());
} } /// <summary>
/// 更新Excel表格
/// </summary>
/// <param name="outputFile">需更新的excel表格路径</param>
/// <param name="sheetname">sheet名</param>
/// <param name="updateData">需更新的数据</param>
/// <param name="coluids">需更新的列号</param>
/// <param name="rowid">需更新的开始行号</param>
public static void UpdateExcel(string outputFile, string sheetname, string[][] updateData, int[] coluids, int rowid)
{
FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read); HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile);
readfile.Close();
ISheet sheet1 = hssfworkbook.GetSheet(sheetname);
for (int j = ; j < coluids.Length; j++)
{
for (int i = ; i < updateData[j].Length; i++)
{
try
{
if (sheet1.GetRow(i + rowid) == null)
{
sheet1.CreateRow(i + rowid);
}
if (sheet1.GetRow(i + rowid).GetCell(coluids[j]) == null)
{
sheet1.GetRow(i + rowid).CreateCell(coluids[j]);
}
sheet1.GetRow(i + rowid).GetCell(coluids[j]).SetCellValue(updateData[j][i]);
}
catch (Exception ex)
{
// wl.WriteLogs(ex.ToString());
}
}
}
try
{
FileStream writefile = new FileStream(outputFile, FileMode.Create);
hssfworkbook.Write(writefile);
writefile.Close();
}
catch (Exception ex)
{
//wl.WriteLogs(ex.ToString());
}
} /// <summary>
/// 更新Excel表格
/// </summary>
/// <param name="outputFile">需更新的excel表格路径</param>
/// <param name="sheetname">sheet名</param>
/// <param name="updateData">需更新的数据</param>
/// <param name="coluid">需更新的列号</param>
/// <param name="rowid">需更新的开始行号</param>
public static void UpdateExcel(string outputFile, string sheetname, double[] updateData, int coluid, int rowid)
{
FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read); HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile);
ISheet sheet1 = hssfworkbook.GetSheet(sheetname);
for (int i = ; i < updateData.Length; i++)
{
try
{
if (sheet1.GetRow(i + rowid) == null)
{
sheet1.CreateRow(i + rowid);
}
if (sheet1.GetRow(i + rowid).GetCell(coluid) == null)
{
sheet1.GetRow(i + rowid).CreateCell(coluid);
} sheet1.GetRow(i + rowid).GetCell(coluid).SetCellValue(updateData[i]);
}
catch (Exception ex)
{
//wl.WriteLogs(ex.ToString());
throw;
}
}
try
{
readfile.Close();
FileStream writefile = new FileStream(outputFile, FileMode.Create, FileAccess.Write);
hssfworkbook.Write(writefile);
writefile.Close();
}
catch (Exception ex)
{
//wl.WriteLogs(ex.ToString());
} } /// <summary>
/// 更新Excel表格
/// </summary>
/// <param name="outputFile">需更新的excel表格路径</param>
/// <param name="sheetname">sheet名</param>
/// <param name="updateData">需更新的数据</param>
/// <param name="coluids">需更新的列号</param>
/// <param name="rowid">需更新的开始行号</param>
public static void UpdateExcel(string outputFile, string sheetname, double[][] updateData, int[] coluids, int rowid)
{
FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read); HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile);
readfile.Close();
ISheet sheet1 = hssfworkbook.GetSheet(sheetname);
for (int j = ; j < coluids.Length; j++)
{
for (int i = ; i < updateData[j].Length; i++)
{
try
{
if (sheet1.GetRow(i + rowid) == null)
{
sheet1.CreateRow(i + rowid);
}
if (sheet1.GetRow(i + rowid).GetCell(coluids[j]) == null)
{
sheet1.GetRow(i + rowid).CreateCell(coluids[j]);
}
sheet1.GetRow(i + rowid).GetCell(coluids[j]).SetCellValue(updateData[j][i]);
}
catch (Exception ex)
{
//wl.WriteLogs(ex.ToString());
}
}
}
try
{
FileStream writefile = new FileStream(outputFile, FileMode.Create);
hssfworkbook.Write(writefile);
writefile.Close();
}
catch (Exception ex)
{
//wl.WriteLogs(ex.ToString());
}
} #endregion #region 读取Excel文件,获取有多少个Sheet数
/// <summary>
/// 读取Excel文件,获取有多少个Sheet数
/// </summary>
/// <param name="filePath">文件地址</param>
/// <returns></returns>
public static int GetSheetNumber(string filePath)
{
int number = ;
try
{
FileStream readfile = new FileStream(filePath, FileMode.Open, FileAccess.Read); HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile);
number = hssfworkbook.NumberOfSheets; }
catch (Exception exception)
{
//wl.WriteLogs(exception.ToString());
}
return number;
} #endregion #region 获取Excel文件中,Sheet表单的名字列表
/// <summary>
/// 获取Excel文件中,Sheet表单的名字列表
/// </summary>
/// <param name="filePath">文件地址</param>
/// <returns></returns>
public static ArrayList GetSheetName(string filePath)
{
ArrayList arrayList = new ArrayList();
try
{
FileStream readfile = new FileStream(filePath, FileMode.Open, FileAccess.Read); HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile);
for (int i = ; i < hssfworkbook.NumberOfSheets; i++)
{
arrayList.Add(hssfworkbook.GetSheetName(i));
}
}
catch (Exception exception)
{
//wl.WriteLogs(exception.ToString());
}
return arrayList;
} #endregion #region 是否是数字
/// <summary>
/// 是否是数字
/// </summary>
/// <param name="message"></param>
/// <param name="result"></param>
/// <returns></returns>
public static bool IsNumeric(String message, out double result)
{
Regex rex = new Regex(@"^[-]?\d+[.]?\d*$");
result = -;
if (rex.IsMatch(message))
{
result = double.Parse(message);
return true;
}
else
return false; } #endregion #region Excel2007 的导入 导出
/// <summary>
/// 将Excel文件中的数据读出到DataTable中(xlsx)
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public static DataTable ExcelToTableForXLSX(string file)
{
DataTable dt = new DataTable();
using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
{
XSSFWorkbook xssfworkbook = new XSSFWorkbook(fs);
ISheet sheet = xssfworkbook.GetSheetAt(); //表头
IRow header = sheet.GetRow(sheet.FirstRowNum);
List<int> columns = new List<int>();
for (int i = ; i < header.LastCellNum; i++)
{
object obj = GetValueTypeForXLSX(header.GetCell(i) as XSSFCell);
if (obj == null || obj.ToString() == string.Empty)
{
dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
//continue;
}
else
dt.Columns.Add(new DataColumn(obj.ToString()));
columns.Add(i);
}
//数据
for (int i = sheet.FirstRowNum + ; i <= sheet.LastRowNum; i++)
{
DataRow dr = dt.NewRow();
bool hasValue = false;
foreach (int j in columns)
{
dr[j] = GetValueTypeForXLSX(sheet.GetRow(i).GetCell(j) as XSSFCell);
if (dr[j] != null && dr[j].ToString() != string.Empty)
{
hasValue = true;
}
}
if (hasValue)
{
dt.Rows.Add(dr);
}
}
}
return dt;
} /// <summary>
/// 将DataTable数据导出到Excel文件中(xlsx)
/// </summary>
/// <param name="dt"></param>
/// <param name="file"></param>
public static void TableToExcelForXLSX(DataTable dt, string file)
{
XSSFWorkbook xssfworkbook = new XSSFWorkbook();
ISheet sheet = xssfworkbook.CreateSheet("Test"); //表头
IRow row = sheet.CreateRow();
for (int i = ; i < dt.Columns.Count; i++)
{
ICell cell = row.CreateCell(i);
cell.SetCellValue(dt.Columns[i].ColumnName);
} //数据
for (int i = ; i < dt.Rows.Count; i++)
{
IRow row1 = sheet.CreateRow(i + );
for (int j = ; j < dt.Columns.Count; j++)
{
ICell cell = row1.CreateCell(j);
cell.SetCellValue(dt.Rows[i][j].ToString());
}
} //转为字节数组
MemoryStream stream = new MemoryStream();
xssfworkbook.Write(stream);
var buf = stream.ToArray(); //保存为Excel文件
using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write))
{
fs.Write(buf, , buf.Length);
fs.Flush();
}
} /// <summary>
/// 获取单元格类型(xlsx)
/// </summary>
/// <param name="cell"></param>
/// <returns></returns>
private static object GetValueTypeForXLSX(XSSFCell cell)
{
if (cell == null)
return null;
switch (cell.CellType)
{
case CellType.Blank: //BLANK:
return null;
case CellType.Boolean: //BOOLEAN:
return cell.BooleanCellValue;
case CellType.Numeric: //NUMERIC:
return cell.NumericCellValue;
case CellType.String: //STRING:
return cell.StringCellValue;
case CellType.Error: //ERROR:
return cell.ErrorCellValue;
case CellType.Formula: //FORMULA:
default:
return "=" + cell.CellFormula;
}
} #endregion }
}
ExcelNpoiHelper
使用NPOI 2.1.1读取EXCEL2003/2007返回DataTable的更多相关文章
- C#读取txt文件返回DATATABLE
//1.打开资源管理器 OpenFileDialog open = new OpenFileDialog(); if (open.ShowDialog() == DialogResult.OK) { ...
- NPOI读取Excel2003,2007
using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Lin ...
- C# 如何使用NPOI操作Excel以及读取合并单元格等
C#操作Excel方法有很多,以前用的需要电脑安装office才能用,但因为版权问题公司不允许安装office.所以改用NPOI进行Excel操作,基本上一些简单的Excel操作都没有问题,读写合并单 ...
- NPOI操作excel之读取excel数据
NPOI 是 POI 项目的 .NET 版本.POI是一个开源的Java读写Excel.WORD等微软OLE2组件文档的项目. 一.下载引用 去NPOI官网http://npoi.codeplex. ...
- NPOI 2.0 Excel读取显示
NPOI 2.0 Excel读取显示 最近接到需求,需要把excel表格里的数据原样展示到web页面,主要是满足随意跨行跨列. 之前用过一点NPOI,不过接触的不太多,趁这次机会再熟悉一下.由于操 ...
- web系统数据导出功能设计实现(导出excel2003/2007 word pdf zip等)
web系统数据导出功能设计实现(导出excel2003/2007 word pdf zip等) 前言 我们在做web系统中,导出也是很常用的一个功能,如果每一个数据列表都要对应写一个导出的方法不太现实 ...
- NPOI 导入Excel和读取Excel
1.整个Excel表格叫做工作表:WorkBook(工作薄),包含的叫页(工作表):Sheet:行:Row:单元格Cell. 2.NPOI是POI的C#版本,NPOI的行和列的index都是从0开始 ...
- C#中NPOI操作excel之读取和写入excel数据
一.下载引用 下载需要引用的dll,即:NPOI.dll,NPOI.OOXML.dll,NPOI.OpenXml4Net.dll,ICSharpCode.SharpZipLib.dll(office2 ...
- java使用poi.3.10读取excel 2007以上版本(xlsx格式)
1.在使用过程中,一直报错 throw new ClassNotFoundException(name);原因:没有导入xmlbeans-2.6.0.jar包,建议在使用poi时,将所有包都导入进工程 ...
随机推荐
- MySQL的连接方式
连接MySQL操作是连接进程和MySQL数据库实例进行通信.从开发的角度来说,本质上是进程通信.常用的进程通信方式有管道.命名管道.命名字.TCP/IP套接字.Unix域名套接字.MySQL提供的连接 ...
- 分层 DAO层,Service层,Controller层、View层
前部分摘录自:http://blog.csdn.net/zdwzzu2006/article/details/6053006 DAO层:DAO层主要是做数据持久层的工作,负责与数据库进行联络的一些任务 ...
- 获取访问MySQL的应用
接到业务需求,要我统计哪个应用访问了哪些表,一般来讲可以通过: 1.show full processlist; 2.SELECT HOST FROM information_schema.proce ...
- amazeui笔记-CSS 布局相关
CSS 等分网格: 说明:.am-avg-sm-2 数字表示几等分 会将子元素 <li>的宽度设置为 50%. 只能用于 <ul> / <ol> 结构 辅助类: ...
- 利用PHP的debug_backtrace函数,实现PHP文件权限管理、动态加载
简述 可能大家都知道,php中有一个函数叫debug_backtrace,它可以回溯跟踪函数的调用信息,可以说是一个调试利器. 好,来复习一下 01 one(); 02 03 function one ...
- Intent的使用
1.普通Intent跳转 Intent intent_intent = new Intent(MainActivity.this,IntentActivity.class); startActivit ...
- Chrome , Firfox 不支持fireEvent的方法
转自:http://bossdai.iteye.com/blog/2111458 Chrome , Firfox 不支持fireEvent的方法 可以使用dispatchEvent的方法替代, 直接给 ...
- JavaScript内置对象与原生对象【转】
原文:https://segmentfault.com/a/1190000002634958 内置对象与原生对象 内置(Build-in)对象与原生(Naitve)对象的区别在于:前者总是在引擎初始化 ...
- java使用lock实现一个简单的死锁程序
import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; public ...
- JAVA基础之——序列化和反序列化
1 概念 序列化,将java对象转换成字节序列的过程. 反序列化,将字节序列恢复成java对象的过程. 2 为什么要序列化? 2.1 实现数据持久化,当对象创建后,它就会一直在,但是在程序终止时,这个 ...