NPOI操作Excel 005:写入空Excel(Winform版)

摘要:
NPOI操作Excel005:写入空Excel(Winform版)==分割==前文写了一个BS版本号的导出Excel的样例(http://blog.csdn.net/yysyangyangyangshan/article/details/47904119)。对于CS版在保存的地方有少许修改。直接看代码例如以下:privatevoidbutton1_Click(objectsender,EventArgse){//要保存的内容。此处用代码生成的内容,而在实际中能够是数据库读取的,//亦或是页面输入的内容DataTabledt=newDataTable();dt.Columns.Add("序号");dt.Columns.Add("姓名");dt.Columns.Add("年龄");dt.Columns.Add("职位");for(inti=0;i<5;i++){DataRowrow=dt.NewRow();row["序号"]=i+1;row["姓名"]="Test"+i;row["年龄"]=25+i;row["职位"]=i%2==0?"project师":"经理";dt.Rows.Add(row);}//为了更好的看怎样使用NPOI。此处显示两行标题。//显示标题能够看怎样合并单元格stringmainTitle="主标题";stringsecondTitle="副标题";//保存的Excel路径,文件名称用guid生成stringfileIndex=System.AppDomain.CurrentDomain.BaseDirectory;stringtempExcel=fileIndex+@"ExcelFile{0}.xls";tempExcel=string.Format(tempExcel,System.Guid.NewGuid());introwIndex=0;//操作Excel的几个主要对象。此处声明HSSFWorkbookworkbook=newHSSFWorkbook();HSSFSheetsheet=workbook.CreateSheet();//row0和row1是两行标题HSSFRowrow0=sheet.CreateRow(rowIndex);HSSFCellcell0=row0.CreateCell(0);cell0.SetCellValue(mainTitle);HSSFCellStylestyle=workbook.CreateCellStyle();style.Alignment=CellHorizontalAlignment.CENTER;HSSFFontfont=workbook.CreateFont();font.Boldweight=short.MaxValue;style.SetFont(font);cell0.CellStyle=style;//此处合并单元格sheet.AddMergedRegion(newNPOI.HSSF.Util.CellRangeAddress(rowIndex,rowIndex,0,5));rowIndex++;HSSFRowrow1=sheet.CreateRow(rowIndex);HSSFCellcell1=row1.CreateCell(0);cell1.SetCellValue(secondTitle);cell1.CellStyle=style;sheet.AddMergedRegion(newNPOI.HSSF.Util.CellRangeAddress(rowIndex,rowIndex,0,5));//由于列名已经指定。占一行rowIndex++;//这一行显示表头HSSFRowrow2=sheet.CreateRow(rowIndex);introw2cellIndex=0;foreach(DataColumncolindt.Columns){HSSFCellcell=row2.CreateCell(row2cellIndex);cell.SetCellValue(col.ColumnName.ToString());row2cellIndex++;}rowIndex++;//datatable的内容for(inti=0;i<dt.Rows.Count;i++){HSSFRowrow=sheet.CreateRow(rowIndex);foreach(DataColumncolindt.Columns){row.CreateCell(col.Ordinal).SetCellValue(dt.Rows[i][col].ToString());}rowIndex++;}//使用文件流保存MemoryStreamms=newMemoryStream();workbook.Write(ms);ms.Flush();ms.Position=0;workbook=null;sheet=null;FolderBrowserDialogdialog=newFolderBrowserDialog();dialog.Description="请选择文件路径";if(dialog.ShowDialog()==DialogResult.OK){stringsaveFile=dialog.SelectedPath+@"TestExcel.xls";using(FileStreamfs=newFileStream(tempExcel,FileMode.Create,FileAccess.ReadWrite)){ms.WriteTo(fs);}File.Copy(tempExcel,saveFile,true);MessageBox.Show("导出成功。");}if(File.Exists(tempExcel)){File.Delete(tempExcel);}ms.Close();}使用保存对话框进行保存:FolderBrowserDialogdialog=newFolderBrowserDialog();dialog.Description="请选择文件路径";if(dialog.ShowDialog()==DialogResult.OK){stringsaveFile=dialog.SelectedPath+@"TestExcel.xls";using(FileStreamfs=newFileStream(tempExcel,FileMode.Create,FileAccess.ReadWrite)){ms.WriteTo(fs);}File.Copy(tempExcel,saveFile,true);MessageBox.Show("导出成功!");}这样在窗体中也能够实现导出Excel。project下载:http://download.csdn.net/detail/yysyangyangyangshan/9039017
前文写了一个BS版本号的导出Excel的样例(http://blog.csdn.net/yysyangyangyangshan/article/details/47904119)。对于CS版在保存的地方有少许修改。直接看代码例如以下:
      private void button1_Click(object sender, EventArgs e)
        {
            //要保存的内容。此处用代码生成的内容,而在实际中能够是数据库读取的,
            //亦或是页面输入的内容

            DataTable dt = new DataTable();

            dt.Columns.Add("序号");

            dt.Columns.Add("姓名");

            dt.Columns.Add("年龄");

            dt.Columns.Add("职位");

            for (int i = 0; i < 5; i++)
            {
                DataRow row = dt.NewRow();

                row["序号"] = i + 1;

                row["姓名"] = "Test" + i;

                row["年龄"] = 25 + i;

                row["职位"] = i % 2 == 0 ? "project师" : "经理";

                dt.Rows.Add(row);
            }
            //为了更好的看怎样使用NPOI。此处显示两行标题。
            //显示标题能够看怎样合并单元格
            string mainTitle = "主标题";

            string secondTitle = "副标题";

            //保存的Excel路径,文件名称用guid生成
            string fileIndex = System.AppDomain.CurrentDomain.BaseDirectory;

            string tempExcel = fileIndex + @"ExcelFile{0}.xls";

            tempExcel = string.Format(tempExcel, System.Guid.NewGuid());

            int rowIndex = 0;

            //操作Excel的几个主要对象。此处声明
            HSSFWorkbook workbook = new HSSFWorkbook();

            HSSFSheet sheet = workbook.CreateSheet();

            //row0和row1是两行标题
            HSSFRow row0 = sheet.CreateRow(rowIndex);

            HSSFCell cell0 = row0.CreateCell(0);

            cell0.SetCellValue(mainTitle);

            HSSFCellStyle style = workbook.CreateCellStyle();

            style.Alignment = CellHorizontalAlignment.CENTER;

            HSSFFont font = workbook.CreateFont();

            font.Boldweight = short.MaxValue;

            style.SetFont(font);

            cell0.CellStyle = style;

            //此处合并单元格
            sheet.AddMergedRegion(new NPOI.HSSF.Util.CellRangeAddress(rowIndex, rowIndex, 0, 5));

            rowIndex++;

            HSSFRow row1 = sheet.CreateRow(rowIndex);

            HSSFCell cell1 = row1.CreateCell(0);

            cell1.SetCellValue(secondTitle);

            cell1.CellStyle = style;

            sheet.AddMergedRegion(new NPOI.HSSF.Util.CellRangeAddress(rowIndex, rowIndex, 0, 5));

            //由于列名已经指定。占一行
            rowIndex++;

            //这一行显示表头
            HSSFRow row2 = sheet.CreateRow(rowIndex);

            int row2cellIndex = 0;

            foreach (DataColumn col in dt.Columns)
            {
                HSSFCell cell = row2.CreateCell(row2cellIndex);

                cell.SetCellValue(col.ColumnName.ToString());

                row2cellIndex++;
            }

            rowIndex++;

            //datatable的内容
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                HSSFRow row = sheet.CreateRow(rowIndex);

                foreach (DataColumn col in dt.Columns)
                {
                    row.CreateCell(col.Ordinal).SetCellValue(dt.Rows[i][col].ToString());

                }

                rowIndex++;
            }

            //使用文件流保存
            MemoryStream ms = new MemoryStream();

            workbook.Write(ms);

            ms.Flush();

            ms.Position = 0;

            workbook = null;

            sheet = null;

          

            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "请选择文件路径";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                string saveFile = dialog.SelectedPath+@"TestExcel.xls";

                using (FileStream fs = new FileStream(tempExcel, FileMode.Create, FileAccess.ReadWrite))
                 {
                     ms.WriteTo(fs);
                 }

                File.Copy(tempExcel, saveFile, true);

                MessageBox.Show("导出成功。");
            }

            if (File.Exists(tempExcel))
            {
                File.Delete(tempExcel);
            }

            ms.Close();
        }

使用保存对话框进行保存:
         FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "请选择文件路径";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                string saveFile = dialog.SelectedPath+@"TestExcel.xls";


                using (FileStream fs = new FileStream(tempExcel, FileMode.Create, FileAccess.ReadWrite))
                 {
                     ms.WriteTo(fs);
                 }


                File.Copy(tempExcel, saveFile, true);


                MessageBox.Show("导出成功!");
            }
这样在窗体中也能够实现导出Excel。
project下载:http://download.csdn.net/detail/yysyangyangyangshan/9039017

免责声明:文章转载自《NPOI操作Excel 005:写入空Excel(Winform版)》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇.Net 程序集 签名工具sn.exe 密钥对SNK文件 最基本的用法.net 必知下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

随便看看

powerdesigner与数据库之间的连接

useUnicode=true&characterEncoding=UT8&serverTimezone=UTC 9JDBCdriverjarfiles:指定连接的jar包路径。测试连接。连接成功。进入工作区。3.2 3.2powerdesigner连接到oracle。其原理与连接MySQL的原理相同。在已安装的oracle下找到ojdbc1...

iOS学习——内存泄漏检查及原因分析

由于我刚刚加入项目团队,我不熟悉所讨论的模块的代码,所以当我遇到问题时,我感到非常困难。此外,作为一名iOS新手,我真的不知道如何排除内存泄漏以及原因。因此,我也借此机会研究了iOS开发中内存泄漏的故障排除方法和原因分析。尽管当前的iOS开发基本上采用ARC模式进行内存管理,但如果不小心,就会发生内存泄漏。...

IPI 通信(SMP)【转】

在MIPS架构下的IPI通信被关闭和中断后,IPIMIPS接口结构平台也将被发送_ smp_Ops{void;void;…}IPI通信是多个处理器之间的通信。send_ ipi_Single:一对一聊天send_ ipi_Mask:Mask posting,Mask表示Mask posting/*Octeon Tellanothercore of Lushi...

kettle的job中运行每行

有时,在运行作业中的每一行时,我们需要多次执行作业或转换。假设我们需要导入从开始日期到昨天的所有旧数据。手动执行作业是痛苦和错误的。Kettle可以首先计算正确的日期,然后根据每个日期执行导入作业。在主作业中,返回日期转换首先运行,实际导入数据的作业在转换后运行。它是一个子作业,负责运行每个输入日期。子作业接收每行的“date”日期参数并执行它。在演示示例中...

windows命令行下批量拷贝同一后缀的文件到另外一个目录

一个目录下有许多文件夹,您希望将每个文件夹下的wmv文件复制到另一个目录。如果用鼠标打开一个文件,复制一个,然后打开另一个,一个一个操作起来非常麻烦。一段时间后,可以实现xcopy命令:例如,复制中的所有文件。Cdisk x1目录下的wmv格式到Ddisk x2:xcopyc:x1目录。wmv/sd:x2命令将x1下的子目录复制到x2。如果只想复制文件,则不...

MongoDB 查看集合的统计信息

--1查看集合的统计信息srs0:“size”:“ok”:可以理解为集合名称计数:集合中的文档总数大小:连续分配的数据块索引:最近分配的块的大小paddingFactor:所有索引索引的总大小大小:--2显示rs0:db。东西。stats(1024)(KB);{“ns”:“count”:“size”:“indexSize”:...