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的更多相关文章

  1. C#读取txt文件返回DATATABLE

    //1.打开资源管理器 OpenFileDialog open = new OpenFileDialog(); if (open.ShowDialog() == DialogResult.OK) { ...

  2. NPOI读取Excel2003,2007

    using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Lin ...

  3. C# 如何使用NPOI操作Excel以及读取合并单元格等

    C#操作Excel方法有很多,以前用的需要电脑安装office才能用,但因为版权问题公司不允许安装office.所以改用NPOI进行Excel操作,基本上一些简单的Excel操作都没有问题,读写合并单 ...

  4. NPOI操作excel之读取excel数据

    NPOI 是 POI 项目的 .NET 版本.POI是一个开源的Java读写Excel.WORD等微软OLE2组件文档的项目.  一.下载引用 去NPOI官网http://npoi.codeplex. ...

  5. NPOI 2.0 Excel读取显示

    NPOI 2.0 Excel读取显示   最近接到需求,需要把excel表格里的数据原样展示到web页面,主要是满足随意跨行跨列. 之前用过一点NPOI,不过接触的不太多,趁这次机会再熟悉一下.由于操 ...

  6. web系统数据导出功能设计实现(导出excel2003/2007 word pdf zip等)

    web系统数据导出功能设计实现(导出excel2003/2007 word pdf zip等) 前言 我们在做web系统中,导出也是很常用的一个功能,如果每一个数据列表都要对应写一个导出的方法不太现实 ...

  7. NPOI 导入Excel和读取Excel

    1.整个Excel表格叫做工作表:WorkBook(工作薄),包含的叫页(工作表):Sheet:行:Row:单元格Cell. 2.NPOI是POI的C#版本,NPOI的行和列的index都是从0开始 ...

  8. C#中NPOI操作excel之读取和写入excel数据

    一.下载引用 下载需要引用的dll,即:NPOI.dll,NPOI.OOXML.dll,NPOI.OpenXml4Net.dll,ICSharpCode.SharpZipLib.dll(office2 ...

  9. java使用poi.3.10读取excel 2007以上版本(xlsx格式)

    1.在使用过程中,一直报错 throw new ClassNotFoundException(name);原因:没有导入xmlbeans-2.6.0.jar包,建议在使用poi时,将所有包都导入进工程 ...

随机推荐

  1. 部署herko小记

    1 先执行如下 heroku run rake db:migrate

  2. 关于禁止html缓存

    在现代的浏览器里,为了增强用户体验,浏览器一般都会把网页上所需的静态文件缓存到本地,再次刷新的时候则无需再重新加载,但是我们有时候就是不需要浏览器缓存这些文件,而是每次都从服务器端读取数据,可以用以下 ...

  3. WPF中使用相对资源来进行绑定,数据源是通过DataContext来指定的

    1. 最外层是Window是对象,Window的ItemsControl使用了ItemsTemplate,然后在ItemsTemplate中要绑定Language属性, 而整个Window的数据源是通 ...

  4. jstack 结果查看

    首先可以用jstack -l pid >sample.dump把java进程的运行栈dump出来. 还可以用grep java.lang.Thread.State sample.dump | a ...

  5. Hardware Emulation Platform (硬件仿真平台) 在IC验证中的运用情况如何?

    三个EDA公司都有自己的hardware emulation verification platform: Cadence Palladium, Synopsys ZeBu, Mentor Veloc ...

  6. [PY3]——内置数据结构(7)——字典及其常用操作

    字典及其常用操作Xmind图 关于字典 字典是一种key-value结构 字典是无序的 字典的定义 # {}大括号可以直接定义一个空字典 In [1]: d={};type(d) Out[1]: di ...

  7. java调用C++代码

    一.在要使用到C++代码的类文件中声明一个native方法,例如: public class TestNative{ public native void test(); } 二.javac编译此ja ...

  8. json跨域问题

    一.跨域问题的原因: 1 浏览器的检查 2 跨域 3 XMLHttpRequest请求 二.跨域问题的解决: 1 禁止浏览器检查: 使用dos命令,在启动浏览器的时候,加一个参数: chrome -- ...

  9. CentOS虚拟机不能联网状况下yum方式从本地安装软件包

    大家都知道yum是linux下一个非常好用的软件安装/卸载软件,它方便操作,而且最厉害的是可以解决令人头疼的包依赖关系.但是若是你的linux不能联网,若想使用yum安装软件,可以依照下面的方法. 1 ...

  10. Docker学习(六): 网络使用与配置

    特别声明: 博文主要是学习过程中的知识整理,以便之后的查阅回顾.部分内容来源于网络(如有摘录未标注请指出).内容如有差错,也欢迎指正! =============系列文章============= 1 ...