一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

利用C#实现Excel导入、导出实例教程

时间:2015-08-07 编辑:简简单单 来源:一聚教程网

1. 介绍

1.1 第三方类库:NPOI

说明:NPOI是POI项目的.NET 版本,可用于ExcelWord的读写操作。

优点:不用装Office环境。

下载地址:http://npoi.codeplex.com/releases

1.2 Excel结构介绍

工作簿(Workbook):每个Excel文件可理解为一个工作簿。

工作表(Sheet):一个工作簿(Workbook)可以包含多个工作表。

行(row):一个工作表(Sheet)可以包含多个行。


2. Excel导入

2.1 操作流程


2.2 NPOI操作代码

说明:把Excel文件转换为List

步骤:

①读取Excel文件并以此初始化一个工作簿(Workbook);

②从工作簿上获取一个工作表(Sheet);默认为工作薄的第一个工作表;

③遍历工作表所有的行(row);默认从第二行开始遍历,第一行(序号0)为单元格头部;

④遍历行的每一个单元格(cell),根据一定的规律赋值给对象的属性。

代码:

+ View Code

2.3 C#逻辑操作代码

说明:对Excel转换后的List进行后续操作;如:检测有效性、持久化存储等等

步骤:

①调用2.2代码,把Excel文件转换为List。

②对List进行有效性检测:必填项是否为空、是否有重复记录等等。

③对List进行持久化存储操作。如:存储到数据库

④返回操作结果。

代码:

public void ImportExcel(HttpContext context)
{
    StringBuilder errorMsg = new StringBuilder(); // 错误信息
    try
    {
 
        #region 1.获取Excel文件并转换为一个List集合
 
        // 1.1存放Excel文件到本地服务器
        HttpPostedFile filePost = context.Request.Files["filed"]; // 获取上传的文件
        string filePath = ExcelHelper.SaveExcelFile(filePost); // 保存文件并获取文件路径
 
        // 单元格抬头
        // key:实体对象属性名称,可通过反射获取值
        // value:属性对应的中文注解
        Dictionary cellheader = new Dictionary {
            { "Name", "姓名" },
            { "Age", "年龄" },
            { "GenderName", "性别" },
            { "TranscriptsEn.ChineseScores", "语文成绩" },
            { "TranscriptsEn.MathScores", "数学成绩" },
        };
 
        // 1.2解析文件,存放到一个List集合里
        List enlist = ExcelHelper.ExcelToEntityList(cellheader, filePath, out errorMsg);
 
        #endregion
 
        #region 2.对List集合进行有效性校验
 
        #region 2.1检测必填项是否必填
 
        for (int i = 0; i < enlist.Count; i++)
        {
            UserEntity en = enlist[i];
            string errorMsgStr = "第" + (i + 1) + "行数据检测异常:";
            bool isHaveNoInputValue = false; // 是否含有未输入项
            if (string.IsNullOrEmpty(en.Name))
            {
                errorMsgStr += "姓名列不能为空;";
                isHaveNoInputValue = true;
            }
            if (isHaveNoInputValue) // 若必填项有值未填
            {
                en.IsExcelVaildateOK = false;
                errorMsg.AppendLine(errorMsgStr);
            }
        }
 
        #endregion
 
        #region 2.2检测Excel中是否有重复对象
 
        for (int i = 0; i < enlist.Count; i++)
        {
            UserEntity enA = enlist[i];
            if (enA.IsExcelVaildateOK == false) // 上面验证不通过,不进行此步验证
            {
                continue;
            }
 
            for (int j = i + 1; j < enlist.Count; j++)
            {
                UserEntity enB = enlist[j];
                // 判断必填列是否全部重复
                if (enA.Name == enB.Name)
                {
                    enA.IsExcelVaildateOK = false;
                    enB.IsExcelVaildateOK = false;
                    errorMsg.AppendLine("第" + (i + 1) + "行与第" + (j + 1) + "行的必填列重复了");
                }
            }
        }
 
        #endregion
 
        // TODO:其他检测
 
        #endregion
 
        // 3.TODO:对List集合持久化存储操作。如:存储到数据库
         
        // 4.返回操作结果
        bool isSuccess = false;
        if (errorMsg.Length == 0)
        {
            isSuccess = true; // 若错误信息成都为空,表示无错误信息
        }
        var rs = new { success = isSuccess,  msg = errorMsg.ToString(), data = enlist };
        System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
        context.Response.ContentType = "text/plain";
        context.Response.Write(js.Serialize(rs)); // 返回Json格式的内容
    }
    catch (Exception ex)
    {
     throw ex;
    }
}

3. Excel导出

3.1 导出流程


3.2 NPOI操作代码

说明:把List转换为Excel

步骤:

①创建一个工作簿(Workbook);

②在工作簿上创建一个工作表(Sheet);

③在工作表上创建第一行(row),第一行为列头,依次写入cellHeard的值(做为列名)。

④循环遍历List集合,每循环一遍创建一个行(row),然后根据cellHeard的键(属性名称)依次从List中的实体对象取值存放到单元格内。

代码:

/// 
/// 实体类集合导出到Excle2003
/// 
/// 单元头的Key和Value:{ { "UserName", "姓名" }, { "Age", "年龄" } };
/// 数据源
/// 工作表名称
/// 文件的下载地址
public static string EntityListToExcel2003(Dictionary cellHeard, IList enList, string sheetName)
{
    try
    {
        string fileName = sheetName + "-" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xls"; // 文件名称
        string urlPath = "UpFiles/ExcelFiles/" + fileName; // 文件下载的URL地址,供给前台下载
        string filePath = HttpContext.Current.Server.MapPath("\\" + urlPath); // 文件路径
 
        // 1.检测是否存在文件夹,若不存在就建立个文件夹
        string directoryName = Path.GetDirectoryName(filePath);
        if (!Directory.Exists(directoryName))
        {
            Directory.CreateDirectory(directoryName);
        }
 
        // 2.解析单元格头部,设置单元头的中文名称
        HSSFWorkbook workbook = new HSSFWorkbook(); // 工作簿
        ISheet sheet = workbook.CreateSheet(sheetName); // 工作表
        IRow row = sheet.CreateRow(0);
        List keys = cellHeard.Keys.ToList();
        for (int i = 0; i < keys.Count; i++)
        {
            row.CreateCell(i).SetCellValue(cellHeard[keys[i]]); // 列名为Key的值
        }
 
        // 3.List对象的值赋值到Excel的单元格里
        int rowIndex = 1; // 从第二行开始赋值(第一行已设置为单元头)
        foreach (var en in enList)
        {
            IRow rowTmp = sheet.CreateRow(rowIndex);
            for (int i = 0; i < keys.Count; i++) // 根据指定的属性名称,获取对象指定属性的值
            {
                string cellValue = ""; // 单元格的值
                object properotyValue = null; // 属性的值
                System.Reflection.PropertyInfo properotyInfo = null; // 属性的信息
 
                // 3.1 若属性头的名称包含'.',就表示是子类里的属性,那么就要遍历子类,eg:UserEn.UserName
                if (keys[i].IndexOf(".") >= 0)
                {
                    // 3.1.1 解析子类属性(这里只解析1层子类,多层子类未处理)
                    string[] properotyArray = keys[i].Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries);
                    string subClassName = properotyArray[0]; // '.'前面的为子类的名称
                    string subClassProperotyName = properotyArray[1]; // '.'后面的为子类的属性名称
                    System.Reflection.PropertyInfo subClassInfo = en.GetType().GetProperty(subClassName); // 获取子类的类型
                    if (subClassInfo != null)
                    {
                        // 3.1.2 获取子类的实例
                        var subClassEn = en.GetType().GetProperty(subClassName).GetValue(en, null);
                        // 3.1.3 根据属性名称获取子类里的属性类型
                        properotyInfo = subClassInfo.PropertyType.GetProperty(subClassProperotyName);
                        if (properotyInfo != null)
                        {
                            properotyValue = properotyInfo.GetValue(subClassEn, null); // 获取子类属性的值
                        }
                    }
                }
                else
                {
                    // 3.2 若不是子类的属性,直接根据属性名称获取对象对应的属性
                    properotyInfo = en.GetType().GetProperty(keys[i]);
                    if (properotyInfo != null)
                    {
                        properotyValue = properotyInfo.GetValue(en, null);
                    }
                }
 
                // 3.3 属性值经过转换赋值给单元格值
                if (properotyValue != null)
                {
                    cellValue = properotyValue.ToString();
                    // 3.3.1 对时间初始值赋值为空
                    if (cellValue.Trim() == "0001/1/1 0:00:00" || cellValue.Trim() == "0001/1/1 23:59:59")
                    {
                        cellValue = "";
                    }
                }
 
                // 3.4 填充到Excel的单元格里
                rowTmp.CreateCell(i).SetCellValue(cellValue);
            }
            rowIndex++;
        }
 
        // 4.生成文件
        FileStream file = new FileStream(filePath, FileMode.Create);
        workbook.Write(file);
        file.Close();
 
        // 5.返回下载路径
        return urlPath;
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

3.3 C#逻辑操作代码

说明:对Excel转换后的List进行后续操作;如:检测有效性、持久化存储等等

步骤:

①获取List集合。

②调用3.2,将List转换为Excel文件。

③服务器存储Excel文件并返回下载链接。

代码:

public void ExportExcel(HttpContext context)
{
    try
    {
        // 1.获取数据集合
        List enlist = new List() {
            new UserEntity{Name="刘一",Age=22,Gender="Male",TranscriptsEn=new TranscriptsEntity{ChineseScores=80,MathScores=90}},
            new UserEntity{Name="陈二",Age=23,Gender="Male",TranscriptsEn=new TranscriptsEntity{ChineseScores=81,MathScores=91} },
            new UserEntity{Name="张三",Age=24,Gender="Male",TranscriptsEn=new TranscriptsEntity{ChineseScores=82,MathScores=92} },
            new UserEntity{Name="李四",Age=25,Gender="Male",TranscriptsEn=new TranscriptsEntity{ChineseScores=83,MathScores=93} },
            new UserEntity{Name="王五",Age=26,Gender="Male",TranscriptsEn=new TranscriptsEntity{ChineseScores=84,MathScores=94} },
        };
 
        // 2.设置单元格抬头
        // key:实体对象属性名称,可通过反射获取值
        // value:Excel列的名称
        Dictionary cellheader = new Dictionary {
            { "Name", "姓名" },
            { "Age", "年龄" },
            { "GenderName", "性别" },
            { "TranscriptsEn.ChineseScores", "语文成绩" },
            { "TranscriptsEn.MathScores", "数学成绩" },
        };
 
        // 3.进行Excel转换操作,并返回转换的文件下载链接
        string urlPath = ExcelHelper.EntityListToExcel2003(cellheader, enlist, "学生成绩");
        System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
        context.Response.ContentType = "text/plain";
        context.Response.Write(js.Serialize(urlPath)); // 返回Json格式的内容
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

3.4 代码分析

核心代码主要是cellheader与List之间的映射关系:


4. 源码下载

4.1 运行图






另一个关于在C#中关于excel的导入和导出操作,也是非常实用的


一、先来看看最常见的导入操作吧!

private void Import()
{  
      //打开excel选择框
      OpenFileDialog frm = new OpenFileDialog();
       frm.Filter = "Excel文件(*.xls,xlsx)|*.xls;*.xlsx";
       if (frm.ShowDialog() == DialogResult.OK)
       {
               
          string excelName = frm.FileName;
          Workbook excel = new Workbook(excelName);
          List importyString=GetImportExcelRoute(excel);
        }
}

 

//循环遍历获取excel的中每行每列的值  
public List GetImportExcelRoute(Workbook excel)
        {
            int icount = excel.Worksheets.Count;
            List routList = new List();
            for (int i = 0; i < icount; i++)
            {
                Worksheet sheet = excel.Worksheets[i];
                Cells cells = sheet.Cells;
                int rowcount = cells.MaxRow;
                int columncount = cells.MaxColumn;
                int routNameColumn = 0;
                int routAttachColumn = 0;
                int routDescColumn = 0;
                int routMesgColumn = 0;
               //获取标题所在的列
                if (rowcount > 0 && columncount > 0)
                {
                    //找到对应的列信息
                    int r0 = 2;
                    for (int c = 0; c <= columncount; c++)
                    {
                        string strVal = cells[r0, c].StringValue.Trim();
                        if (strVal == "备注")
                        {
                            routDescColumn = c;
                            break;
                        }
                    }
                    r0 = 3;
                    for (int c = 0; c <= columncount; c++)
                    {
                        //获取文本框内容
                        string strVal = cells[r0, c].StringValue.Trim();
                        if (strVal == "审批明细事项")
                        {
                            routNameColumn = c;
                        }
                        if (strVal == "细项")
                        {
                            routMesgColumn = c;
                        }
                        if (strVal == "前置条件及工作要求")
                        {
                            routAttachColumn = c;
                        }
                    }
                     //找到对应标题列下面的值
                    if (routNameColumn > 0 && routAttachColumn > 0 && routDescColumn > 0)
                    {//在从对应的列中找到对应的值
                        for (int r = 4; r <= rowcount; r++)
                        {
                            string[] str = new string[6];
                            string strRoutName = "";
                            string strRoutMesg = "";
                            string strRoutAttach = "";
                            string strRoutDesc = "";
                            string strRoutRole = "";
                            string strRoutPro = "";
                            for (int c = 0; c <= columncount; c++)
                            {
                                int mergcolumncount = 0;
                                int mergrowcount = 0;
                                bool ismerged = cells[r, c].IsMerged;//是否合并单元格 
                                if (ismerged)
                                {
                                    Range range = cells[r, c].GetMergedRange();
                                    if (range != null)
                                    {
                                        mergcolumncount = range.ColumnCount;
                                        mergrowcount = range.RowCount;
                                    }
                                }
                                //获取文本框内容
                                string strVal = "";
                                strVal = cells[r, c].StringValue.Trim();
                                if (c == routNameColumn)
                                {
                                    strRoutName = strVal;
                                    if (mergrowcount > 1 && string.IsNullOrEmpty(strRoutName))
                                    {
                                        strRoutName = GetRoutName(routList, 0);
                                    }
                                }
                                if (c == routMesgColumn)
                                {
                                    strRoutMesg = strVal;
                                    if (mergrowcount > 1 && string.IsNullOrEmpty(strRoutMesg))
                                    {
                                        strRoutMesg = GetRoutName(routList, 1);
                                    }
                                }
                                if (c == routAttachColumn)
                                {
                                    strRoutAttach = strVal;
                                }
                                if (c == routDescColumn)
                                {
                                    strRoutDesc = strVal;
                                }
                           }
                   }
 }




可以看到导入是比较简单的,就是循环读取每行每列的值,可以看到文中有不少Cells这个属性,这个需要用到第三方的插件:using Aspose.Cells;需要在网上下载一个 Aspose.Cells的dll.

二、导出,就是将数据组合好后导成excel格式:

private void Export()
{
    SaveFileDialog frm = new SaveFileDialog();
    frm.Filter = "Excel文件(*.xls,xlsx)|*.xls;*.xlsx";
    frm.FileName = flowName + ".xlsx";
    if (frm.ShowDialog() == DialogResult.OK)
    {
        string strpath = frm.FileName;
        Workbook workbook = null;
       string strpath = _exportFlowRoutExcelPath;
       if (File.Exists(strpath))
       {
          workbook = new Workbook(strpath);
        }
        else
        {
           workbook = new Workbook();
       }
       Worksheet sheet = workbook.Worksheets[0]; //工作表
       Cells cells = sheet.Cells;//单元格
       string str="";//获取要导出的数据
      
       
          try
          {                 
             RoutExportToExcel(workbook,cells,str);
                        
                MessageBox.Show("导出成功!");
            }
             catch                        
              {
                MessageBox.Show("导出失败!");
            }
        }
    }
 }



 

public void RoutExportToExcel(Workbook workbook, Cells cells,string str)
{
   分别得到行和列
    int routCount =0;//;
    int rowcount = 4 + routCount;
    int columnCount = 25;
    for (int i = 0; i < rowcount; i++)
    {
        Style style = SettingCellStyle(workbook, cells);
        if (i == 0)
        {
            style.Font.Color = Color.Red;
            style.Font.Size = 16;
            cells.Merge(0, 0, 1, columnCount);//合并单元格
            cells[i, 0].PutValue("综合管线决策授权体系事项");//填写内容
            cells[0, 0].SetStyle(style);//给单元格关联样式
            cells.SetRowHeight(0, 38);//设置行高
            cells.SetColumnWidth(1, 20);//设置列宽
        }
        if (i > 0)
        {
            string routeName = "";
            string routeNote = "";
            string routeCondition = "";
            string guid = "";
            if (i > 3)
            {
                cells.SetRowHeight(i, 42);//设置行高
                JsonObject routJsonObj = routeJsonArray[i - 4] as JsonObject;
                routeName = routJsonObj["routName"] == null ? "" : routJsonObj["routName"].ToString();
                routeNote = routJsonObj["note"] == null ? "" : routJsonObj["note"].ToString();
                routeCondition = routJsonObj["condition"] == null ? "" : routJsonObj["condition"].ToString();
                guid = routJsonObj["guid"] == null ? "" : routJsonObj["guid"].ToString();
            }
            for (int j = 0; j < columnCount; j++)
            {
                cells[i, j].SetStyle(style);//给单元格关联样式
                //填充行
                if (i > 3)
                {
                    if (j == 0)//序号
                    {
                        cells[i, j].PutValue(i - 3);//填写内容
                    }
                    else if (j == 4 || j == 5 || j == 24)//审批明细事项 细项 备注
                    {
                        FillExcelRoutProperty(i,j,style,cells,routeName,routeNote,routeCondition);
                    }
                    else if (j == 2 || j == 3 || j == 6 || j == 7 || j == 8 || j == 10 || j == 11 || j == 12 || j == 13)//类别、分类、层级或板块、地区、管线、前置条件责任部门及责任人、审核校对验收责任部门及责任人、具体审核校对验收要求、发起人
                    {
                        FillExcelRoutExtProperty(i, j, guid, style, cells,routExtPropertyJsonArray);
                    }
                    else if (j >= 14 && j <= 23)//路由角色变量(从审批人1到终审人)
                    {
                        FillExcelRoutRoleVal(i,j,guid,style,cells,routRoleValjsonArray);
                    }
                    else if (j == 9)//前置条件及工作要求
                    {
                        FillExcelRoutPreConditon(i,j,guid,style,cells,routPreConditonJsonArray);
                    }
                }
                else
                {
                   SettingCellStyleAndLine(cells, i, j);//设置excel的标题行和列
                }
            }
        }
    }
}
/// 
/// 设置单元格样式及线条
/// 
/// 
/// 
/// 
public void SettingCellStyleAndLine(Cells cells, int i, int j)
{
    if (i == 1)
    {
        if (j == 0)
        {
            cells.Merge(1, j, 3, 1);//合并单元格
            cells[i, j].PutValue("序号");//填写内容
            cells.SetColumnWidth(j, 5);//设置列宽
        }
        if (j == 1)
        {
            cells.Merge(1, j, 3, 1);//合并单元格
            cells.SetColumnWidth(j, 5);//设置列宽
        }
   }
}



/// 
/// 设置单元格的样式
/// 
/// 
/// 
/// 
public Style SettingCellStyle(Workbook workbook, Cells cells)
{
    Style style = workbook.Styles[workbook.Styles.Add()];//新增样式
    style.HorizontalAlignment = TextAlignmentType.Center;//文字居中
    style.Font.Name = "宋体";//文字字体
    style.Font.Size = 10;//文字大小
    style.IsLocked = false;//单元格解锁
    style.Font.IsBold = false;//粗体
    style.ForegroundColor = Color.FromArgb(255, 255, 255);//设置背景色
    style.Pattern = BackgroundType.Solid; //设置背景样式
    style.IsTextWrapped = true;//单元格内容自动换行
    style.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin; //应用边界线 左边界线
    style.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin; //应用边界线 右边界线
    style.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin; //应用边界线 上边界线
    style.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin; //应用边界线 下边界线
    return style;
}


热门栏目