winform怎样把数据输出到固定格式的excel,就是一个复杂的报表,求一个详细的例子,谢谢

.Net技术 码拜 9年前 (2015-07-18) 1212次浏览 0个评论

winform怎样把数据输出到固定格式的excel,就是一个复杂的报表

5分

#1

用dev的gridcontrol 自带导出功能

#2

能详细的讲讲吗,我是第一次接触报表
5分

#3

可以将查询出来的结果数据,通过第三方的 NPOI  导出到excel, 用这个, 不要求目标机器上安装 office 软件。

具体方法这里有:
http://www.cnblogs.com/relax/p/3586355.html

#4

我看资料有的说用宏做,能做吗,能不能详细讲讲,NPOI的我很笨 不太能看明白

#5

我下到了一个npoi的类文件,不会用。太笨了,也不知道能不能满足我的需求
using System;
using System.Web;
using System.IO;
using System.Data;

namespace ShareProject.Servie
{
    /// <summary>
    ///Fso 的摘要说明
    /// </summary>
    public class Excel
    {
        public Excel()
        {
            //
            //TODO: 在此处添加构造函数逻辑
            //
        }
        /// <summary>
        /// 把文件名转为
        /// </summary>
        /// <param name=”filename”></param>
        /// <returns></returns>
        public static string Get_NewFileName(string filename)
        {
            string userAgent = HttpContext.Current.Request.UserAgent;
            string new_filename = HttpUtility.UrlEncode(filename);
            string rtn = “filename=”” + new_filename + “””; 
            if (userAgent != null)
            {
                userAgent = userAgent.ToLower();
                // IE浏览器,只能采用URLEncoder编码 
                //if (userAgent.IndexOf(“msie”) != -1)
                //{
                //    rtn = “filename=”” + new_filename + “””;
                //}
                // Opera浏览器只能采用filename* 
                if (userAgent.IndexOf(“opera”) != -1)
                {
                    rtn = “filename*=UTF-8″”””” + new_filename;
                }
                // Safari浏览器,只能采用ISO编码的中文输出 
                else if (userAgent.IndexOf(“safari”) != -1)
                {
                    //rtn = “filename=”” + new String(System.Text.Encoding.UTF8.GetBytes(filename), “ISO8859-1”) + “””;
                    //rtn = “filename=”” + new String(filename.ToCharArray(“UTF-8”), “ISO8859-1”) + “””;  
                }
                // Chrome浏览器,只能采用MimeUtility编码或ISO编码的中文输出 
                else if (userAgent.IndexOf(“applewebkit”) != -1)
                {
                    //new_filename = MimeUtility.encodeText(filename, “UTF8”, “B”); 
                    //rtn = “filename=”” + new_filename + “””;
                }
                // FireFox浏览器,可以使用MimeUtility或filename*或ISO编码的中文输出 
                else if (userAgent.IndexOf(“mozilla”) != -1)
                {
                    rtn = “filename*=UTF-8″”””” + new_filename;
                }
            }
            return rtn;

        }
        /// <summary>
        /// 使用NPOI导出Excel,服务器不需要安装Office插件,注意服务器上需要添加asp.net用户的权限
        /// </summary>
        /// <param name=”attachName”>要在服务器上保留的文件物理地址,为null或空值时,不会在服务器保留文件</param>
        /// <param name=”excelname”>输出的文件名</param>
        /// <param name=”SourceTable”>要输出的源数据DataTable</param>
        /// <param name=”Width”>自定义每一列的宽度,为null时,将自动适应</param>
        /// <param name=”Column”>自定义每一列的名称,为null时,将自动把DataTable里的字段标题设为标题</param>
        /// <param name=”sortid”>是否加序号,true为自动加序号,false为不用</param>
        /// <param name=”SheetName”>excel的Sheet表名,为空默认是Sheet0</param>

#6

接上
  public static void DataTableToExcel(string attachName, string excelname, DataTable SourceTable, int[] Width, string[] Column,bool sort,string SheetName)
        {
            MemoryStream ms = new MemoryStream();
            NPOI.HSSF.UserModel.HSSFWorkbook workbook = new NPOI.HSSF.UserModel.HSSFWorkbook();
            NPOI.SS.UserModel.ISheet sheet;
            if (SheetName == “” || SheetName == null) sheet = workbook.CreateSheet();
            else sheet = workbook.CreateSheet(SheetName);
            NPOI.SS.UserModel.IRow headerRow = sheet.CreateRow(0);
            if (Column != null && SourceTable.Columns.Count == Column.Length)
            {
                //使用自定义标题
                if (sort) headerRow.CreateCell(0).SetCellValue(“序号”);
                for (int i = 0; i < Column.Length; i++)
                {
                    if (sort) headerRow.CreateCell(i + 1).SetCellValue(Column[i]);
                    else headerRow.CreateCell(i).SetCellValue(Column[i]);
                }
            }
            else
            {
                //使用datatable的字段名做标题
                if (sort) headerRow.CreateCell(0).SetCellValue(“ID”);
                for (int i = 0; i < SourceTable.Columns.Count; i++)
                {
                    if (sort) headerRow.CreateCell(i + 1).SetCellValue(SourceTable.Columns[i].Caption);
                    else headerRow.CreateCell(i).SetCellValue(SourceTable.Columns[i].Caption);
                }
            }
            int rowIndex = 1;
            foreach (DataRow row in SourceTable.Rows)
            {
                NPOI.SS.UserModel.IRow dataRow = sheet.CreateRow(rowIndex);
                if (sort) dataRow.CreateCell(0).SetCellValue(rowIndex);
                for (int i = 0; i < SourceTable.Columns.Count; i++)
                {
                    //循环把值写入到Excel
                    if (sort) dataRow.CreateCell(i + 1).SetCellValue(row[i].ToString());
                    else dataRow.CreateCell(i).SetCellValue(row[i].ToString());
                }
                rowIndex++;
            }
            if (sort) sheet.AutoSizeColumn(0);
            if (Width != null)
            {
                //使用自定义宽度
                for (int i = 0; i < Width.Length; i++)
                {
                    if (sort) sheet.SetColumnWidth(i + 1, Width[i] * 256);
                    else sheet.SetColumnWidth(i, Width[i] * 256);
                }
            }
            else
            {
                //自动适用宽度
                for (int i = 0; i < SourceTable.Columns.Count; i++)
                {
                    if (sort) sheet.AutoSizeColumn(i + 1);
                    else sheet.AutoSizeColumn(i);
                }
            }
            workbook.Write(ms);
            ms.Flush();
            ms.Position = 0;
            sheet = null;
            headerRow = null;
            workbook = null;
            if (attachName == “” || attachName == null)
            {
                //直接输出文件,不在服务器保留文件
                byte[] buffer = ms.ToArray();
                int length;
                long dataToRead = ms.Length;
                excelname = Get_NewFileName(excelname + “.xls”);
                HttpContext.Current.Response.ContentType = “application/octet-stream”;
                HttpContext.Current.Response.AddHeader(“Content-Disposition”, “attachment; ” + excelname);
                while (dataToRead > 0)
                {
                    if (HttpContext.Current.Response.IsClientConnected)
                    {
                        length = ms.Read(buffer, 0, 1000);
                        HttpContext.Current.Response.OutputStream.Write(buffer, 0, length);
                        HttpContext.Current.Response.Flush();
                        buffer = new Byte[10000];
                        dataToRead = dataToRead – length;
                    }
                    else
                    {
                        dataToRead = -1;
                    }
                }
                buffer = null;
                ms = null;
            }
            else
            {
                //服务器保留文件
                FileStream fs = new FileStream(attachName, FileMode.Create, FileAccess.Write);
                byte[] data = ms.ToArray();
                fs.Write(data, 0, data.Length);
                fs.Flush();
                fs.Close();
                data = null;
                ms = null;
                fs = null;
                Down.DownFile(attachName, excelname + “.xls”);
                //excelname = Get_NewFileName(excelname + “.xls”);
                //HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding(“UTF-8”);
                //HttpContext.Current.Response.AppendHeader(“content-disposition”, “attachment;” + excelname);
                //HttpContext.Current.Response.ContentType = “Application/excel”;
                //HttpContext.Current.Response.WriteFile(attachName);
                //HttpContext.Current.Response.End();
            }
        }
        /// <summary>
        /// 使用NPOI导出Excel,只保留在服务器,不加载下载程序,服务器不需要安装Office插件,注意服务器上需要添加asp.net用户的权限
        /// </summary>
        /// <param name=”attachName”>要在服务器上保留的文件物理地址</param>
        /// <param name=”SourceTable”>要输出的源数据DataTable</param>
        /// <param name=”Width”>自定义每一列的宽度,为null时,将自动适应</param>
        /// <param name=”Column”>自定义每一列的名称,为null时,将自动把DataTable里的字段标题设为标题</param>
        /// <param name=”sortid”>是否加序号,true为自动加序号,false为不用</param>
        /// <param name=”SheetName”>excel的Sheet表名,为空默认是Sheet0</param>
        public static void DataTableToExcel2(string attachName, DataTable SourceTable, int[] Width, string[] Column, bool sort, string SheetName)
        {
            MemoryStream ms = new MemoryStream();
            NPOI.HSSF.UserModel.HSSFWorkbook workbook = new NPOI.HSSF.UserModel.HSSFWorkbook();
            NPOI.SS.UserModel.ISheet sheet;
            if (SheetName == “” || SheetName == null) sheet = workbook.CreateSheet();
            else sheet = workbook.CreateSheet(SheetName);
            NPOI.SS.UserModel.IRow headerRow = sheet.CreateRow(0);
            if (Column != null && SourceTable.Columns.Count == Column.Length)
            {
                //使用自定义标题
                if (sort) headerRow.CreateCell(0).SetCellValue(“序号”);
                for (int i = 0; i < Column.Length; i++)
                {
                    if (sort) headerRow.CreateCell(i + 1).SetCellValue(Column[i]);
                    else headerRow.CreateCell(i).SetCellValue(Column[i]);
                }
            }
            else
            {
                //使用datatable的字段名做标题
                if (sort) headerRow.CreateCell(0).SetCellValue(“ID”);
                for (int i = 0; i < SourceTable.Columns.Count; i++)
                {
                    if (sort) headerRow.CreateCell(i + 1).SetCellValue(SourceTable.Columns[i].Caption);
                    else headerRow.CreateCell(i).SetCellValue(SourceTable.Columns[i].Caption);
                }
            }
            int rowIndex = 1;
            foreach (DataRow row in SourceTable.Rows)
            {
                NPOI.SS.UserModel.IRow dataRow = sheet.CreateRow(rowIndex);
                if (sort) dataRow.CreateCell(0).SetCellValue(rowIndex);
                for (int i = 0; i < SourceTable.Columns.Count; i++)
                {
                    //循环把值写入到Excel表
                    if (sort) dataRow.CreateCell(i + 1).SetCellValue(row[i].ToString());
                    else dataRow.CreateCell(i).SetCellValue(row[i].ToString());
                }
                rowIndex++;
            }
            if (sort) sheet.AutoSizeColumn(0);
            if (Width != null)
            {
                //使用自定义宽度
                for (int i = 0; i < Width.Length; i++)
                {
                    if (sort) sheet.SetColumnWidth(i + 1, Width[i] * 256);
                    else sheet.SetColumnWidth(i, Width[i] * 256);
                }
            }
            else
            {
                //自动适用宽度
                for (int i = 0; i < SourceTable.Columns.Count; i++)
                {
                    if (sort) sheet.AutoSizeColumn(i + 1);
                    else sheet.AutoSizeColumn(i);
                }
            }
            workbook.Write(ms);
            ms.Flush();
            ms.Position = 0;
            sheet = null;
            headerRow = null;
            workbook = null;
            FileStream fs = new FileStream(attachName, FileMode.Create, FileAccess.Write);
            byte[] data = ms.ToArray();
            fs.Write(data, 0, data.Length);
            fs.Flush();
            fs.Close();
            data = null;
            ms = null;
            fs = null;
        }
        public static void DataTable2Csv(string attachName, DataTable tab, string[] tabname)
        {
            StringWriter sw = new StringWriter();
            string tempstr = “”;
            for (int col = 0; col < tabname.Length; col++)
            {
                if (tempstr == “”) tempstr = tabname[col].Replace(“,”, “”);
                else tempstr += “,” + tabname[col];
            }
            sw.WriteLine(tempstr);
            foreach (DataRow dr in tab.Rows)
            {
                tempstr = “”;
                for (int colIndex = 0; colIndex < tab.Columns.Count; colIndex++)
                {
                    if (tempstr == “”) tempstr = dr[colIndex].ToString();
                    else tempstr += “,” + dr[colIndex].ToString();
                }
                sw.WriteLine(tempstr);
            }

#7

说起复杂报表 ReportViewer就是一高手器啊 不用写代码 图形化设计 还自带输出excel word pdf功能 简直是杀人灭口 输出报表 必备良药

#8

回复7楼:

是要下一个控件吗,我是vs2008,有没有具体用的教程,谢谢

#9

回复8楼:

2013有 然后之前没有的话你可以用水晶报表
这种复杂报表的需求不止你一个人有

#10

回复9楼:

网上可以下下来用吗,客户要求是尽量不用水晶报表

30分

#11

回复10楼:

客户说不要用 那可以啊 这种功能自己重新做一个要加钱 

#12

谁有详细一点的讲解操作啊,我是太笨啦

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明winform怎样把数据输出到固定格式的excel,就是一个复杂的报表,求一个详细的例子,谢谢
喜欢 (0)
[1034331897@qq.com]
分享 (0)

文章评论已关闭!