C# 使用 NPOI 库读写 Excel 文件
public class ExcelHelper { /// <summary> /// Datable导出成Excel /// </summary> /// <param name="dt">导出存放文件夹路径</param> /// <param name="Route">文件夹路径</param> /// <param name="file">导出路径(包括文件名与扩展名),注:年月日时分秒+文件名</param> public static void TableToExcel(DataTable dt, string Route, string file) { string[] fileArr = file.Split(new char[] { '.' }); file = fileArr[0] + DateTime.Now.ToString("yyyyMMddHHmmss") + "." + fileArr[1]; IWorkbook workbook; string fileExt = Path.GetExtension(file).ToLower(); if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(); } else if (fileExt == ".xls") { workbook = new HSSFWorkbook(); } else { workbook = null; } if (workbook == null) { return; } ISheet sheet = string.IsNullOrEmpty(dt.TableName) ? workbook.CreateSheet("Sheet1") : workbook.CreateSheet(dt.TableName); //设置列宽 //sheet.SetColumnWidth(0, 15 * 256); //sheet.SetColumnWidth(1, 15 * 256); //sheet.SetColumnWidth(2, 15 * 256); //sheet.SetColumnWidth(3, 15 * 256); //sheet.SetColumnWidth(4, 15 * 256); //sheet.SetColumnWidth(5, 25 * 256); //sheet.SetColumnWidth(6, 25 * 256); //sheet.SetColumnWidth(7, 30 * 256); //sheet.SetColumnWidth(8, 15 * 256); //sheet.SetColumnWidth(9, 15 * 256); //sheet.SetColumnWidth(10, 15 * 256); //sheet.SetColumnWidth(12, 15 * 256); //for (int i = 0; i < dt.Rows.Count; i++) //{ // sheet.SetColumnWidth(i, 20 * 256); //} //表头 IRow row = sheet.CreateRow(0); for (int i = 0; i < dt.Columns.Count - 1; i++) { ICell cell = row.CreateCell(i); cell.SetCellValue(dt.Columns[i].ColumnName); } //数据 for (int i = 0; i < dt.Rows.Count; i++) { IRow row1 = sheet.CreateRow(i + 1); for (int j = 0; j < dt.Columns.Count - 1; j++) { ICell cell = row1.CreateCell(j); cell.SetCellValue(dt.Rows[i][j].ToString()); } } //转为字节数组 MemoryStream stream = new MemoryStream(); workbook.Write(stream); var buf = stream.ToArray(); //如找不到文件夹则创建 if (!Directory.Exists(Route)) { Directory.CreateDirectory(Route); } //保存为Excel文件 using (FileStream fs = new FileStream(Route + file, FileMode.Create, FileAccess.Write)) { fs.Write(buf, 0, buf.Length); fs.Flush(); } HttpResponse response = HttpContext.Current.Response; response.Clear(); response.ClearHeaders(); response.ClearContent(); response.Buffer = true; response.AddHeader("content-disposition", string.Format("attachment; FileName={0}", file)); response.Charset = "GB2312"; response.ContentEncoding = Encoding.GetEncoding("GB2312"); response.ContentType = MimeMapping.GetMimeMapping(file); response.WriteFile(Route + file); response.Flush(); response.Close(); //HttpResponseBase response = httpContext.Response; //response.Clear(); //response.Buffer = false; //response.AddHeader("Accept-Ranges", "bytes"); //response.AddHeader("Content-Type", GetContentTypeByFileName(fileName)); //response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(Encoding.UTF8.GetBytes(fileName))); //response.AddHeader("Content-Length", buffer.Length.ToString()); //response.OutputStream.Write(buffer, 0, buffer.Length); //response.Flush(); //response.End(); } /// <summary> /// Excel导入成Datable /// </summary> /// <param name="file">导入路径(包含文件名与扩展名)</param> /// <returns></returns> public static DataTable ExcelToTable(string file) { DataTable dt = new DataTable(); IWorkbook workbook; string fileExt = Path.GetExtension(file).ToLower(); using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read)) { //XSSFWorkbook 适用XLSX格式,HSSFWorkbook 适用XLS格式 if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(fs); } else if (fileExt == ".xls") { workbook = new HSSFWorkbook(fs); } else { workbook = null; } if (workbook == null) { return null; } ISheet sheet = workbook.GetSheetAt(0); //表头 IRow header = sheet.GetRow(sheet.FirstRowNum); List<int> columns = new List<int>(); for (int i = 0; i < header.LastCellNum; i++) { object obj = GetValueTypeForXLSX(header.GetCell(i) as XSSFCell);// GetValueType(header.GetCell(i)); if (obj == null || obj.ToString() == string.Empty) { dt.Columns.Add(new DataColumn("Columns" + i.ToString())); } else dt.Columns.Add(new DataColumn(obj.ToString())); columns.Add(i); } //数据 for (int i = sheet.FirstRowNum + 1; 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);// GetValueType(sheet.GetRow(i).GetCell(j)); if (dr[j] != null && dr[j].ToString() != string.Empty) { hasValue = true; } } if (hasValue) { dt.Rows.Add(dr); } } } return dt; } /// <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.DateCellValue; //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; } } }