c# 导入excel处理数据,导出excel报表

这篇博客介绍了如何使用C#进行Excel文件的导入和导出。通过NPOI库,实现了从上传的Excel文件中读取数据到DataTable,并提供了检查文件大小和格式的验证。此外,还提到了用于导出Excel的工具类的使用。
摘要由CSDN通过智能技术生成

c# 导入excel处理数据,导出excel报表

//stemp1=============================

//先上存一个excel文件 接收后解析获得数据

#region 导入excel表并处理数据
///
/// 导入excel表并处理数据
/// api/Schedual/ImportExceltoData
///
///
[HttpPost]
[ActionName(“ImportExceltoData”)]
public IHttpActionResult ImportExceltoData()
{
try
{
PortraitApp = “~/FileLibs/Temp/”;
if (!Directory.Exists(HttpContext.Current.Server.MapPath(PortraitApp)))
{
Directory.CreateDirectory(HttpContext.Current.Server.MapPath(PortraitApp));
}
HttpFileCollection files = HttpContext.Current.Request.Files;
string name = “”;
string filename = “”;
string path = “”;
foreach (string key in files.AllKeys)
{
HttpPostedFile file = files[key];
if (string.IsNullOrEmpty(file.FileName) == false)
{
int length = file.ContentLength;
if (length > 2097152)
{
throw new CustomException(“上传文件超过2M,请将上传文件大小控制在2M内,谢谢”);
}
string extension = file.FileName.Substring(file.FileName.LastIndexOf(‘.’)).ToLower();
if (extension != “.xls”)
{
throw new CustomException(“上传文件扩展名不正确,请上传xls格式的excel表”);
}
name = DateTime.Now.ToStringByDatetime(DateTimeType.yyyyMMddHHmmss) + extension;
//LoginVerifyModels usermodel = GetVerifyModel();
string username = GetVerifyString();
if (!string.IsNullOrEmpty(username))
{
name = username + extension;
}
path = HttpContext.Current.Server.MapPath(PortraitApp) + name;
file.SaveAs(HttpContext.Current.Server.MapPath(PortraitApp) + name);
filename = file.FileName;
}
}
DataTable dt = new ExcelHelper().ExcelToDataTable(path, filename, false);
if (dt == null || dt.Rows.Count < 2)
{ throw new CustomException(“表格数据不能为空”); }

           //此处插入对象到数据库
            List<SchedualInfoModel> list = insertTableSchedual(dt);

            if (list.Count > 0)
                return Json(Success(list));
            else
                return Json(Success("导入失败"));

        }
        catch (CustomException ce)
        {
            return Json(getException(ce.Message));
        }
        catch (Exception ex)
        {
            return Json(getException(ex));
        }
    }

//stemp2=============================

//解析excel表格

#region 通过文件获取信息
    /// <summary>
    /// 将excel中的数据导入到DataTable中
    /// </summary>
    /// <param name="sheetName">excel工作薄sheet的名称</param>
    /// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>
    /// <returns>返回的DataTable</returns>
    public DataTable ExcelToDataTable(string fileName, string sheetName, bool isFirstRowColumn)
    {
        IWorkbook workbook = null;
        FileStream fs = null;
        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 HSSFWorkbook(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);
                }
            }
            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)
                        {
                            string cellValue = cell.StringCellValue;
                            if (cellValue != null)
                            {
                                DataColumn column = new DataColumn(cellValue);
                                data.Columns.Add(column);
                            }
                        }
                    }
                    startRow = sheet.FirstRowNum + 1;
                }
                else
                {
                    firstRow = sheet.GetRow(2);
                    cellCount = firstRow.LastCellNum;
                    for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                    {
                        ICell cell = firstRow.GetCell(i);
                        if (cell != null)
                        {
                            string cellValue = cell.StringCellValue;
                            if (cellValue != null)
                            {
                                DataColumn column = new DataColumn(cellValue);
                                if (i == 0)
                                {
                                    column = new DataColumn("姓名");
                                    data.Columns.Add(column);
                                }
                                else
                                    data.Columns.Add(column);
                            }
                        }
                    }
                    startRow = sheet.FirstRowNum + 2;
                }

                //最后一列的标号
                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
                            dataRow[j] = row.GetCell(j).ToString();

                    }
                    data.Rows.Add(dataRow);
                }
            }

            return data;
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception: " + ex.Message);
            return null;
        }
    }

//stemp0=============================

//导出excel 工具类

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace mofa.commom
{
using NPOI;
using NPOI.HPSF;
using NPOI.HSSF;
using NPOI.HSSF.UserModel;
using NPOI.POIFS;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.Util;
using System.Data;

public class ExcelHelper
{

    /// <summary>
    /// 创建工作簿
    /// </summary>
    /// <param name="fileName">下载文件名</param>
    /// <param name="dt">数据源</param>
    public string CreateSheet(DataTable dt)
    {
        string DataFile = System.Configuration.ConfigurationManager.AppSettings["DataFile"].ToString();
        string filepath = HttpContext.Current.Server.MapPath(DataFile) + DateTime.Now.ToStringByDatetime(DateTimeType.yyyyMMdd) + "\\";
        if (!Directory.Exists(filepath))
        {
            Directory.CreateDirectory(filepath);
        }
        FolderDeal(HttpContext.Current.Server.MapPath(DataFile));

        StringBuilder builder = new StringBuilder();

        string name = System.DateTime.Now.ToStringByDatetime(DateTimeType.yyyyMMddHHmmss) + ".xls";
        string fileName = filepath + name;

        //创建工作薄  
        IWorkbook workbook = new HSSFWorkbook(); ;
        //string extensi
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值