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

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<string[]> importyString=GetImportExcelRoute(excel);        }}
//循环遍历获取excel的中每行每列的值  public List<string[]> GetImportExcelRoute(Workbook excel)
        {
            int icount = excel.Worksheets.Count;

            List<string[]> routList = new List<string[]>();
            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的标题行和列
                        }
                    }
                }
            }
        }
  /// <summary>
        /// 设置单元格样式及线条
        /// </summary>
        /// <param name="cells"></param>
        /// <param name="i"></param>
        /// <param name="j"></param>
        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);//设置列宽
                }
           }
 }
 /// <summary>
        /// 设置单元格的样式
        /// </summary>
        /// <param name="workbook"></param>
        /// <param name="cells"></param>
        /// <returns></returns>
        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;
        }

在C#中关于excel的导入和导出操作的更多相关文章

  1. SpringBoot中关于Excel的导入和导出

    前言   由于在最近的项目中使用Excel导入和导出较为频繁,以此篇博客作为记录,方便日后查阅.本文前台页面将使用layui,来演示对Excel文件导入和导出的效果.本文代码已上传至我的gitHub, ...

  2. 表格类型数据,Excel csv导入,导出操作

    import pandas # 创建表格格式# ad = pandas.DataFrame({"a": range(1, 10), "b": range(10, ...

  3. 前端必读3.0:如何在 Angular 中使用SpreadJS实现导入和导出 Excel 文件

    在之前的文章中,我们为大家分别详细介绍了在JavaScript.React中使用SpreadJS导入和导出Excel文件的方法,作为带给广大前端开发者的"三部曲",本文我们将为大家 ...

  4. excel的导入与导出---通用版

    excel的导入与导出---通用版 web项目关于导入导出的业务场景很常见,最近我就又遇到了这个业务场景.这次将最近半个月做的导入导出总结一下 使用的pom如下,主要还是阿里巴巴的easyexcel依 ...

  5. .net数据库实现Excel的导入与导出

    .net数据库实现Excel的导入与导出 参考路径:https://www.cnblogs.com/splendidme/archive/2012/01/05/2313314.html 1.defau ...

  6. C#中Excel的导入和导出的几种基本方式

    在上一篇(http://www.cnblogs.com/fengchengjushi/p/3369386.html)介绍过,Excel也是数据持久化的一种实现方式.在C#中.我们常常会与Excel文件 ...

  7. Excel报表开发(主要讲Excel的导入和导出)

    一.Excel数据导入 连接字符串Excel2003版: OleDbConnection conn = new OleDbConnection("provider=Microsoft.Jet ...

  8. java实现Excel的导入、导出

    一.Excel的导入 导入可采用两种方式,一种是JXL,另一种是POI,但前者不能读取高版本的Excel(07以上),后者更具兼容性.由于对两种方式都进行了尝试,就都贴出来分享(若有错误,请给予指正) ...

  9. SpringBoot整合easyexcel实现Excel的导入与导出

    导出 在一般不管大的或者小的系统中,各家的产品都一样,闲的无聊的时候都喜欢让我们这些程序员导出一些数据出来供他观赏,非说这是必须需求,非做不可,那么我们就只能苦逼的哼哧哼哧的写bug喽. 之前使用PO ...

随机推荐

  1. [转]让你提升命令行效率的 Bash 快捷键

    生活在 Bash shell 中,熟记以下快捷键,将极大的提高你的命令行操作效率. 编辑命令 Ctrl + a :移到命令行首 Ctrl + e :移到命令行尾 Ctrl + f :按字符前移(右向) ...

  2. 第五章 jQuery中的动画

    通过jQuery中的动画方法,能轻松地为网页添加精彩的视觉效果,给用户一种全新体验. 1.show()方法和hide()方法 该方法的功能与css()方法设置display属性效果相同. 给show( ...

  3. wpf打印控件 实现分页打印控件功能

    因为 要实现打印 wpf  listbox控件  数据特别多 要打印在 几张纸上    找了几天 都没有找到相关的例子 现在 解决了 在这里和大家分享一下 public void print(Fram ...

  4. mac os 10.10 pod install errors

    /System/Library/Frameworks/Ruby.framework/Versions//gems/rake-/bin/rake RUBYARCHDIR=/Library/Ruby/Ge ...

  5. cocos2d-x实战 C++卷 学习笔记--第5章 精灵

    前言: 精灵类是Sprite类.它的子类有PhysicsSprite 和 Skin. PhysicsSprite 是物理引擎精灵类,而Skin是皮肤精灵类,用于骨骼动画. 创建Sprite精灵对象 创 ...

  6. 12天学好C语言——记录我的C语言学习之路(Day 5)

    12天学好C语言--记录我的C语言学习之路 Day 5: 第五天的学习开始了,今天我们主要对几个程序进行编写,让自己充分的熟练编程语言,大量的题目会让自己变的精炼.以一个程序(program 5.1) ...

  7. ESP8266开发课堂之 - 建立一个新项目

    项目架构 ESP8266项目开发并非使用IDE自动管理工程文件,而是使用了诸多第三方程序如Python,以及使用了Makefile管理依赖与控制编译,所以项目的创建与日常维护较为复杂,本篇将详述创建一 ...

  8. [翻译][MVC 5 + EF 6] 9:异步和存储过程

    原文:Async and Stored Procedures with the Entity Framework in an ASP.NET MVC Application 1.为什么使用异步代码: ...

  9. Android-ViewPagerIndicator-master 、Android-PullToRefresh 学习篇

    最近在学习android,然后看到了很多有用的开源库.其中一个就是Android-ViewPagerIndicator :. 这是与ViewPager兼容的一个分页指示器库.分页指示器(Friends ...

  10. Windows Phone 动态改变ListBox样式

    使用ListBox时通常会借助ItemTemplate帮助我们实现更复杂多样的样式显示,体现了Xaml的灵活.如何动态改变变ListBox的样式,实现类似电脑资源管理器中列表显示和图标显示形式的替换. ...