NPOI导出

image
数据库大概如上,没有将全部数据导出来。只是3个字段。
private void button1_Click(object sender, EventArgs e)
        {
            SaveFileDialog sdfExport = new SaveFileDialog();
            sdfExport.Filter = "Excel文件|*.xls";
            if (sdfExport.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            string filename = sdfExport.FileName;
            HSSFWorkbook workbook = new HSSFWorkbook();
            ISheet sheet = workbook.CreateSheet("员工信息");
            IRow rowHeader = sheet.CreateRow(0);
            rowHeader.CreateCell(0, CellType.STRING).SetCellValue("员工姓名");//表头设置
            rowHeader.CreateCell(1, CellType.STRING).SetCellValue("员工电话");
            rowHeader.CreateCell(2, CellType.STRING).SetCellValue("提交时间");
            string conStr = "Data Source=.;Initial CataLog=HM3Data;User Id=sa;Password=qiufeng";
            using (SqlConnection conn = new SqlConnection(conStr))
            {
                string sqlStr = "select * from UserInfo";
                SqlDataAdapter da = new SqlDataAdapter(sqlStr, conStr);
                DataSet ds = new DataSet();
                da.Fill(ds);
                DataTable dt = ds.Tables[0];
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    IRow row = sheet.CreateRow(i + 1);
                    DataRow dr = dt.Rows[i];
                    row.CreateCell(0, CellType.STRING).SetCellValue(dr["UName"].ToString());
                    row.CreateCell(1, CellType.STRING).SetCellValue(dr["Phone"].ToString());
                    ICellStyle styledate = workbook.CreateCellStyle();//日期类型的格式
                    IDataFormat format = workbook.CreateDataFormat();
                    styledate.DataFormat = format.GetFormat("yyyy\"年\"m\"月\"d\"日\"");
                    ICell cell = row.CreateCell(2, CellType.NUMERIC);
                    cell.CellStyle = styledate;
                    cell.SetCellValue(Convert.ToDateTime(dr["SubTime"].ToString()));

                }

            }
            using (Stream stream = File.OpenWrite(filename))
            {
                workbook.Write(stream);
            }

        }
posted on 2013-03-04 21:42  快乐于行  阅读(321)  评论(0编辑  收藏  举报