excel导出 按dataset里的datatable导出一个excel多个sheet 和 datatable导出

//datatable导出
public static void DataTableToExcel(string filename, string sheetName, DataTable table)
        {
            //增加序号列
            //rui.dbHelper.insert序号(table, 0);
            IWorkbook workbook = new HSSFWorkbook();
            ISheet sheet = workbook.CreateSheet(sheetName);
            //设置单元格的样式:水平垂直居中
            ICellStyle style = workbook.CreateCellStyle();
            style.Alignment = HorizontalAlignment.Center;
            style.VerticalAlignment = VerticalAlignment.Center;
            //写标题
            IRow header = sheet.CreateRow(0);
            for (int i = 0; i < table.Columns.Count; i++)
            {
                ICell cell = header.CreateCell(i);
                string value = table.Columns[i].ColumnName;//标题转换
                cell.SetCellValue(value);
                cell.CellStyle = style;
                //sheet.SetColumnWidth(i, 30 * 240);
                //header.CreateCell(i).SetCellValue(table.Columns[i].ColumnName);
            }
            //写数据
            for (int i = 0; i < table.Rows.Count; i++)
            {
                IRow row = sheet.CreateRow(i + 1);//
                for (int j = 0; j < table.Columns.Count; j++)
                {
                    string celltext = table.Rows[i][j].ToString();
                    ICell cell = row.CreateCell(j);
                    cell.SetCellValue(celltext);
                    cell.CellStyle = style;

                }
            }
            //宽度自适应
            for (int columnNum = 0; columnNum < table.Columns.Count; columnNum++)
            {
                int columnWidth = sheet.GetColumnWidth(columnNum) / 256;//获取当前列宽度
                for (int rowNum = 0; rowNum <= sheet.LastRowNum; rowNum++)//在这一列上循环行
                {
                    IRow currentRow = sheet.GetRow(rowNum);
                    ICell currentCell = currentRow.GetCell(columnNum);
                    int length = Encoding.UTF8.GetBytes(currentCell.ToString()).Length;//获取当前单元格的内容宽度
                    if (columnWidth < length + 1)
                    {
                        columnWidth = length + 1;
                    }//若当前单元格内容宽度大于列宽,则调整列宽为当前单元格宽度,后面的+1是我人为的将宽度增加一个字符
                }
                sheet.SetColumnWidth(columnNum, columnWidth * 256);
            }
            // 写入到客户端
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            workbook.Write(ms);
            HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
            HttpContext.Current.Response.Charset = "UTF8";
            //根据不同的浏览器设置对应的文件名
            string attachFilename = "";
            {
                string enCodeFilename = HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8);
                string userAgent = HttpContext.Current.Request.Browser.Browser;
                userAgent = userAgent.ToLower();

                //rui.logTools.log("浏览器类型:" + userAgent);
                //IE浏览器
                if (userAgent.IndexOf("ie") != -1 || userAgent.IndexOf("mozilla") != -1)
                {
                    attachFilename = @"filename=" + enCodeFilename;
                }
                //Opera浏览器只能采用filename*
                else if (userAgent.IndexOf("opera") != -1)
                {
                    attachFilename = @"filename*=UTF-8‘‘" + enCodeFilename;
                }
                //FireFox浏览器
                else if (userAgent.IndexOf("firefox") != -1)
                {
                    attachFilename = @"filename*=" + enCodeFilename;
                }
                //遨游
                else if (userAgent.IndexOf("chrome") != -1)
                {
                    attachFilename = @"filename=" + enCodeFilename;
                }
                else
                {
                    attachFilename = @"filename=" + enCodeFilename;
                }
            }
            HttpContext.Current.Response.AddHeader("Content-Disposition",
                string.Format("attachment;{0}.xls", attachFilename));
            HttpContext.Current.Response.BinaryWrite(ms.ToArray());
            HttpContext.Current.Response.End();
            workbook = null;
            ms.Close();
            ms.Dispose();
        }
public static void DataSetToExcel(string filename, DataSet ds)
        {
            IWorkbook workbook = new HSSFWorkbook();
            for (int i = 0; i < ds.Tables.Count; i++)
            {
                string sheetName = ds.Tables[i].TableName;
                //增加序号列
                //rui.dbHelper.insert序号(table, 0);

                ISheet sheet = workbook.CreateSheet(sheetName);
                //设置单元格的样式:水平垂直居中
                ICellStyle style = workbook.CreateCellStyle();
                style.Alignment = HorizontalAlignment.Center;
                style.VerticalAlignment = VerticalAlignment.Center;
                //写标题
                IRow header = sheet.CreateRow(0);
                for (int j = 0; j < ds.Tables[i].Columns.Count; j++)
                {
                    ICell cell = header.CreateCell(j);
                    string value = ds.Tables[i].Columns[j].ColumnName;//标题转换
                    cell.SetCellValue(value);
                    cell.CellStyle = style;
                    //sheet.SetColumnWidth(i, 30 * 240);
                    //header.CreateCell(i).SetCellValue(table.Columns[i].ColumnName);
                }
                //写数据
                for (int j = 0; j < ds.Tables[i].Rows.Count; j++)
                {
                    IRow row = sheet.CreateRow(j + 1);//
                    for (int k = 0; k < ds.Tables[i].Columns.Count; k++)
                    {
                        string celltext = ds.Tables[i].Rows[i][k].ToString();
                        ICell cell = row.CreateCell(k);
                        cell.SetCellValue(celltext);
                        cell.CellStyle = style;

                    }
                }
                //宽度自适应
                for (int columnNum = 0; columnNum < ds.Tables[i].Columns.Count; columnNum++)
                {
                    int columnWidth = sheet.GetColumnWidth(columnNum) / 256;//获取当前列宽度
                    for (int rowNum = 0; rowNum <= sheet.LastRowNum; rowNum++)//在这一列上循环行
                    {
                        IRow currentRow = sheet.GetRow(rowNum);
                        ICell currentCell = currentRow.GetCell(columnNum);
                        int length = Encoding.UTF8.GetBytes(currentCell.ToString()).Length;//获取当前单元格的内容宽度
                        if (columnWidth < length + 1)
                        {
                            columnWidth = length + 1;
                        }//若当前单元格内容宽度大于列宽,则调整列宽为当前单元格宽度,后面的+1是我人为的将宽度增加一个字符
                    }
                    sheet.SetColumnWidth(columnNum, columnWidth * 256);
                }

            }
            // 写入到客户端
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            workbook.Write(ms);
            HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
            HttpContext.Current.Response.Charset = "UTF8";
            //根据不同的浏览器设置对应的文件名
            string attachFilename = "";
            {
                string enCodeFilename = HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8);
                string userAgent = HttpContext.Current.Request.Browser.Browser;
                userAgent = userAgent.ToLower();

                //rui.logTools.log("浏览器类型:" + userAgent);

                //IE浏览器
                if (userAgent.IndexOf("ie") != -1 || userAgent.IndexOf("mozilla") != -1)
                {
                    attachFilename = @"filename=" + enCodeFilename;
                }
                //Opera浏览器只能采用filename*
                else if (userAgent.IndexOf("opera") != -1)
                {
                    attachFilename = @"filename*=UTF-8‘‘" + enCodeFilename;
                }
                //FireFox浏览器
                else if (userAgent.IndexOf("firefox") != -1)
                {
                    attachFilename = @"filename*=" + enCodeFilename;
                }
                //遨游
                else if (userAgent.IndexOf("chrome") != -1)
                {
                    attachFilename = @"filename=" + enCodeFilename;
                }
                else
                {
                    attachFilename = @"filename=" + enCodeFilename;
                }
            }
            HttpContext.Current.Response.AddHeader("Content-Disposition",
                string.Format("attachment;{0}.xls", attachFilename));

            HttpContext.Current.Response.BinaryWrite(ms.ToArray());
            HttpContext.Current.Response.End();
            workbook = null;
            ms.Close();
            ms.Dispose();

        }
时间: 2024-08-06 15:51:45

excel导出 按dataset里的datatable导出一个excel多个sheet 和 datatable导出的相关文章

使用OpenXml把Excel中的数据导出到DataSet中

public class OpenXmlHelper { /// <summary> /// 读取Excel数据到DataSet中,默认读取所有Sheet中的数据 /// </summary> /// <param name="filePath">Excel文件路径</param> /// <param name="sheetNames">Sheet名称列表,默认为null查询所有Sheet中的数据<

Excel导入DataTable兼容2003-2012(请细心查看注释)以及 DataTable导出Excel(导出格式2003.xls)注释:需要引用NPOI

1.#region Excel导入DataTable兼容2003-2012(请细心查看注释)/// <summary> /// 读取Excel文件到DataSet中/// 注释1:2012导出如报错“ System.InvalidOperationException: 未在本地计算机上注册“microsoft.ACE.oledb.12.0”提供程序.”解决:下载2007 Office system 驱动程序:数据连接组件安装http://download.microsoft.com/downl

Datatable转换成excel并实现导出功能,导出到服务端,提供客户端下载

好久没有写笔记了,写得不好,大家将就看看吧! 这是一个关于导出Excel到服务端指定的文件中供客户去下载的一个方法:首先要获取保存服务器的物理路径,也就是绝对路径,可以使用 HttpContext.Current.Server.MapPath(".");可以获取到.最方便的就是直接用datatable转成Excel格式,当生成文件时,同时向数据库插入一条记录: 代码: public void DataTableTransmissionExcel(bool withHeaders,Dat

c# .Net :Excel NPOI导入导出操作教程之数据库表信息数据导出到一个Excel文件并写到磁盘示例分享

  string sql = @"select * from T_Excel"; ----------------DataTable Star----------------        DataTable dt = SqlHelper.ExecuteDataTable(sql);        if (dt.Rows.Count > 0)        {            //创建工作簿            IWorkbook workbook = new HSSFW

NPOI对Excel的操作(Sheet转DataTable、List&lt;T&gt;)

1 using System.Collections.Generic; 2 using NPOI.HSSF.UserModel; 3 using NPOI.SS.UserModel; 4 using NPOI.XSSF.UserModel; 5 using System.IO; 6 using System.Data; 7 using System; 8 9 namespace CommonHelper 10 { 11 public class ExcelHelper 12 { 13 14 pu

c# 32位机和64位机 读取Excel内容到DataSet

// ----------------------32位机 //注释说明 //ExclePath 为Excel路径 批号 是指Excel文件中某一列必填项 public static DataSet GetDataTableForExcel(String ExclePath) { string strCon = String.Empty; strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ExclePath + &qu

EXCEL数据导入dataset

一.开工必备 1.micorosoft office2007 2.VS2010.Oracle 11 二.界面 三.内部代码 (1)获取数据库连接,定义全局变量 private static string connString = System.Configuration.ConfigurationSettings.AppSettings[ "connStr" ];         DataSet dTable; (2)选择Excel文件导入dataset if(openFileDial

三种从DataTable导入到Excel

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Drawing; using Excel= Microsoft.Office.Interop.Excel;//ASP.NET中Excel的命名空间 using System.Data.SqlCli

读取excel数据到数据库里

用的是jxlJar /** * 读取excel数据到数据库里 */ private void readExcelToDB() { new Thread(new Runnable() { @Override public void run() { try { String filePath = "/sdcard/"; String fileName = "307322.xlsx"; File file = new File(filePath, fileName); F