.NET选择模板添加书签导出Word文档,Web导出至Excel。WordHelp类和ExcelHelp类

前言

最近一个项目中需要添加一个合同信息,不仅要把合同信息数据存入到数据库,还需导出一个word文档的合同用于打印。那么今天就向大家介绍在MVC中如何导出word模板,顺便附加如何将数据表导出至Excel中。

导出word实现步骤

实现大致思路
1:新建一个Word文档合同模板,其次对这个模板进行添加书签名称。
2:将Word文档合同模板更改后缀为.dot 为Word模板
3:将Word文档合同模板 放入项目目录文件
4:在项目中Nuget中下载 Microsoft.Office.Interop.Word 工具包,并添加引用
在这里插入图片描述

5:新建一个处理WordHelp类
6:获取需要填写在合同里的数据,找到Word文档的路径,并对他进行操作且对Word合同模板中的书签名称进行相对应赋值。
7:另存为Word并更改后缀为.doc

(1)首先新建一个合同模板

在这里插入图片描述
大家可以看到这里面有几个需要填写的数据,比如合同号,合同负责人,客户名称,客户身份证号……等。那么这个地方该如何把数据库里的相关数据填充在这个地方呢?添加书签就是最方便的办法。

(2)添加书签

在这里插入图片描述
光标放在指定位置,这里比如合同号:| 。点击插入=》找到书签。这个时候将会弹出书签框。对其添加书签名称,也就是说存放值的书签名称。记得要再次点击书签进行书签名定位。
在这里插入图片描述
好了之后,保存。更改后缀名为.dot。其意思变为Word模板。
这个时候就将它放入项目目录文件中
在这里插入图片描述

项目界面

在这里插入图片描述

后端代码

需要添加的命名空间

using Microsoft.Office.Interop.Word;
using Word = Microsoft.Office.Interop.Word;
using System.Data;
using System.IO;
using System.Text;
  public string Toprint(WordBookPamrs bookPamrs)
        {
    
    
            WriteIntoWord wiw = new WriteIntoWord();
            // 找到合同模板路径 
            string FilePath = Server.MapPath("/Content/docx/Contract.dot");
            // 设置将要保存合同Word的新路径
            string SaveDocPath = Server.MapPath("/Content/docx/Newcon"+ bookPamrs.contract_id+ ".doc");
            // 打开合同模板,并进行操作
            wiw.OpenDocument(FilePath);
            // 向合同模板的 书签名为 “adress” 进行赋值
            wiw.WriteIntoDocument("adress", bookPamrs.adress);
            // 向合同模板的 书签名为 “contract_id” 进行赋值
            wiw.WriteIntoDocument("contract_id", bookPamrs.contract_id);
            // 向合同模板的 书签名为 “cust_name” 进行赋值
            wiw.WriteIntoDocument("cust_name", bookPamrs.cust_name);
            wiw.WriteIntoDocument("ele", bookPamrs.ele);
            wiw.WriteIntoDocument("emp_name", bookPamrs.emp_name);
            wiw.WriteIntoDocument("gas", bookPamrs.gas);
            wiw.WriteIntoDocument("getdate", bookPamrs.getdate);
            wiw.WriteIntoDocument("house_adress", bookPamrs.house_adress);
            wiw.WriteIntoDocument("house_id", bookPamrs.house_id);
            wiw.WriteIntoDocument("idcard_num", bookPamrs.idcard_num);
            wiw.WriteIntoDocument("rent", bookPamrs.rent);
            wiw.WriteIntoDocument("water", bookPamrs.water);
            wiw.Save_CloseDocument(SaveDocPath);
            return SaveDocPath;
        }
        public class WriteIntoWord
        {
    
    
            ApplicationClass app = null;   //定义应用程序对象 
            Document doc = null;   //定义 word 文档对象
            Object missing = System.Reflection.Missing.Value; //定义空变量
            Object isReadOnly = false;
            // 向 word 文档写入数据 
            public void OpenDocument(string FilePath)
            {
    
    
                object filePath = FilePath;//文档路径
                app = new ApplicationClass(); //打开文档 
                doc = app.Documents.Open(ref filePath, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref missing);
                doc.Activate();//激活文档
            }

            /// <summary> 
            /// 域标签,写入域中的内容
            /// </summary> 
            ///<param name="parLableName">域标签</param> 
            /// <param name="parFillName">写入域中的内容</param> 
            //打开word,将对应数据写入word里对应书签域
            public void WriteIntoDocument(string BookmarkName, string FillName)
            {
    
    
                object bookmarkName = BookmarkName;
                Bookmark bm = doc.Bookmarks.get_Item(ref bookmarkName);//返回书签 
                bm.Range.Text = FillName;//设置书签域的内容
            }
            /// <summary> 
            /// 保存并关闭 
            /// </summary> 
            /// <param name="parSaveDocPath">文档另存为的路径</param>
            public void Save_CloseDocument(string SaveDocPath)
            {
    
    
                object savePath = SaveDocPath;  //文档另存为的路径 
                Object saveChanges = app.Options.BackgroundSave;//文档另存为 
                doc.SaveAs(ref savePath, ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing);
                doc.Close(ref saveChanges, ref missing, ref missing);//关闭文档
                app.Quit(ref missing, ref missing, ref missing);//关闭应用程序
            }
        }

注意可能会出现的问题!!!无法嵌入互操作类型" ApplicationClass.请改用适用的接口。

在这里插入图片描述
当出现此问题时,别急===>
在这里插入图片描述
将嵌入互操作类型为False就好了

最后

当然我这边的 WordBookPamrs bookPamrs 他是我要传递数据的实体类,大家可以别弄晕了。
这样基本就OK了。

实现效果图

在这里插入图片描述
当然如果大家还需要进行其他的操作,不一定要进行选择模板。那我为大家提供WordHelp类。

WordHelp类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Word;
using Word = Microsoft.Office.Interop.Word;
using System.Data;
namespace Util.Tool
{
    
    
    /// <summary>
    /// Word 文档操作类
    /// </summary>
    public class WordlHelper
    {
    
    
        private Microsoft.Office.Interop.Word.Application oWordApplic; // a reference to Word application 引用Word应用程序
        private Microsoft.Office.Interop.Word.Document oDoc;                    // a reference to the document 引用文档

        public WordlHelper()
        {
    
    
            // activate the interface with the COM object of Microsoft Word
            //激活与Microsoft Word的COM对象的接口
            oWordApplic = new Microsoft.Office.Interop.Word.Application();
        }

        /// <summary>
        /// 插入图片
        /// </summary>
        /// <param name="picPath"></param>
        public void InsertPicture(string picPath)
        {
    
    
            object missing = System.Reflection.Missing.Value;
            oWordApplic.Selection.InlineShapes.AddPicture(picPath, ref missing, ref missing, ref missing);
        }

        // Open a file (the file must exists) and activate it  打开一个文件(该文件必须存在),并激活它
        public void Open(string strFileName)
        {
    
    
            object fileName = strFileName;
            object readOnly = false;
            object isVisible = true;
            object missing = System.Reflection.Missing.Value;

            oDoc = oWordApplic.Documents.Open(ref fileName, ref missing, ref readOnly,
                ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref isVisible, ref missing, ref missing, ref missing);

            oDoc.Activate();
        }


        // Open a new document打开一个新文档
        public void Open()
        {
    
    
            object missing = System.Reflection.Missing.Value;
            oDoc = oWordApplic.Documents.Add(ref missing, ref missing, ref missing, ref missing);

            oDoc.Activate();
        }




        public void Quit()
        {
    
    
            object missing = System.Reflection.Missing.Value;
            oWordApplic.Application.Quit(ref missing, ref missing, ref missing);
        }

        public void Save()
        {
    
    
            oDoc.Save();
        }

        public void SaveAs(string strFileName)
        {
    
    
            object missing = System.Reflection.Missing.Value;
            object fileName = strFileName;

            oDoc.SaveAs(ref fileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
        }

        // Save the document in HTML format 以HTML格式保存文档
        public void SaveAsHtml(string strFileName)
        {
    
    
            object missing = System.Reflection.Missing.Value;
            object fileName = strFileName;
            object Format = (int)Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML;
            oDoc.SaveAs(ref fileName, ref Format, ref missing, ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
        }



        public void InsertText(string strText)
        {
    
    
            oWordApplic.Selection.TypeText(strText);
        }

        public void InsertLineBreak()
        {
    
    
            oWordApplic.Selection.TypeParagraph();
        }
        public void InsertLineBreak(int nline)
        {
    
    
            for (int i = 0; i < nline; i++)
                oWordApplic.Selection.TypeParagraph();
        }


        // Change the paragraph alignement 更改段落对齐键相
        public void SetAlignment(string strType)
        {
    
    
            switch (strType)
            {
    
    
                case "Center":
                    oWordApplic.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                    break;
                case "Left":
                    oWordApplic.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
                    break;
                case "Right":
                    oWordApplic.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
                    break;
                case "Justify":
                    oWordApplic.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphJustify;
                    break;
            }

        }


        // if you use thif function to change the font you should call it again with 如果您使用此功能来改变字体,你应该再次调用它 
        // no parameter in order to set the font without a particular format 为了不带参数设置字体没有特定的格式
        public void SetFont(string strType)
        {
    
    
            switch (strType)
            {
    
    
                case "Bold":
                    oWordApplic.Selection.Font.Bold = 1;
                    break;
                case "Italic":
                    oWordApplic.Selection.Font.Italic = 1;
                    break;
                case "Underlined":
                    oWordApplic.Selection.Font.Subscript = 0;
                    break;
            }

        }

        // disable all the style  禁用所有的风格
        public void SetFont()
        {
    
    
            oWordApplic.Selection.Font.Bold = 0;
            oWordApplic.Selection.Font.Italic = 0;
            oWordApplic.Selection.Font.Subscript = 0;

        }

        public void SetFontName(string strType)
        {
    
    
            oWordApplic.Selection.Font.Name = strType;

        }

        public void SetFontSize(int nSize)
        {
    
    
            oWordApplic.Selection.Font.Size = nSize;

        }

        public void InsertPagebreak()
        {
    
    
            // VB : Selection.InsertBreak Type:=wdPageBreak
            object pBreak = (int)Microsoft.Office.Interop.Word.WdBreakType.wdPageBreak;
            oWordApplic.Selection.InsertBreak(ref pBreak);
        }

        // Go to a predefined bookmark, if the bookmark doesn't exists the application will raise an error 
        //去到一个预先定义的书签,如果书签不存在应用程序将引发错误
        public void GotoBookMark(string strBookMarkName)
        {
    
    
            // VB :  Selection.GoTo What:=wdGoToBookmark, Name:="nome"
            object missing = System.Reflection.Missing.Value;

            object Bookmark = (int)Microsoft.Office.Interop.Word.WdGoToItem.wdGoToBookmark;
            object NameBookMark = strBookMarkName;
            oWordApplic.Selection.GoTo(ref Bookmark, ref missing, ref missing, ref NameBookMark);
        }

        public void GoToTheEnd()
        {
    
    
            // VB :  Selection.EndKey Unit:=wdStory
            object missing = System.Reflection.Missing.Value;
            object unit;
            unit = Microsoft.Office.Interop.Word.WdUnits.wdStory;
            oWordApplic.Selection.EndKey(ref unit, ref missing);

        }
        public void GoToTheBeginning()
        {
    
    
            // VB : Selection.HomeKey Unit:=wdStory
            object missing = System.Reflection.Missing.Value;
            object unit;
            unit = Microsoft.Office.Interop.Word.WdUnits.wdStory;
            oWordApplic.Selection.HomeKey(ref unit, ref missing);

        }

        public void GoToTheTable(int ntable)
        {
    
    
            //	Selection.GoTo What:=wdGoToTable, Which:=wdGoToFirst, Count:=1, Name:=""
            //    Selection.Find.ClearFormatting
            //    With Selection.Find
            //        .Text = ""
            //        .Replacement.Text = ""
            //        .Forward = True
            //        .Wrap = wdFindContinue
            //        .Format = False
            //        .MatchCase = False
            //        .MatchWholeWord = False
            //        .MatchWildcards = False
            //        .MatchSoundsLike = False
            //        .MatchAllWordForms = False
            //    End With

            object missing = System.Reflection.Missing.Value;
            object what;
            what = Microsoft.Office.Interop.Word.WdUnits.wdTable;
            object which;
            which = Microsoft.Office.Interop.Word.WdGoToDirection.wdGoToFirst;
            object count;
            count = 1;
            oWordApplic.Selection.GoTo(ref what, ref which, ref count, ref missing);
            oWordApplic.Selection.Find.ClearFormatting();

            oWordApplic.Selection.Text = "";


        }

        public void GoToRightCell()
        {
    
    
            // Selection.MoveRight Unit:=wdCell

            object missing = System.Reflection.Missing.Value;
            object direction;
            direction = Microsoft.Office.Interop.Word.WdUnits.wdCell;
            oWordApplic.Selection.MoveRight(ref direction, ref missing, ref missing);
        }

        public void GoToLeftCell()
        {
    
    
            // Selection.MoveRight Unit:=wdCell

            object missing = System.Reflection.Missing.Value;
            object direction;
            direction = Microsoft.Office.Interop.Word.WdUnits.wdCell;
            oWordApplic.Selection.MoveLeft(ref direction, ref missing, ref missing);
        }

        public void GoToDownCell()
        {
    
    
            // Selection.MoveRight Unit:=wdCell

            object missing = System.Reflection.Missing.Value;
            object direction;
            direction = Microsoft.Office.Interop.Word.WdUnits.wdLine;
            oWordApplic.Selection.MoveDown(ref direction, ref missing, ref missing);
        }

        public void GoToUpCell()
        {
    
    
            // Selection.MoveRight Unit:=wdCell

            object missing = System.Reflection.Missing.Value;
            object direction;
            direction = Microsoft.Office.Interop.Word.WdUnits.wdLine;
            oWordApplic.Selection.MoveUp(ref direction, ref missing, ref missing);
        }


        // this function doesn't work 这个功能不起作用
        public void InsertPageNumber(string strType, bool bHeader)
        {
    
    
            object missing = System.Reflection.Missing.Value;
            object alignment;
            object bFirstPage = false;
            object bF = true;
            //if (bHeader == true)
            //WordApplic.Selection.HeaderFooter.PageNumbers.ShowFirstPageNumber = bF;
            switch (strType)
            {
    
    
                case "Center":
                    alignment = Microsoft.Office.Interop.Word.WdPageNumberAlignment.wdAlignPageNumberCenter;
                    //WordApplic.Selection.HeaderFooter.PageNumbers.Add(ref alignment,ref bFirstPage);
                    //Word.Selection objSelection = WordApplic.pSelection;

                    //oWordApplic.Selection.HeaderFooter.PageNumbers.Item(1).Alignment = Microsoft.Office.Interop.Word.WdPageNumberAlignment.wdAlignPageNumberCenter;
                    break;
                case "Right":
                    alignment = Microsoft.Office.Interop.Word.WdPageNumberAlignment.wdAlignPageNumberRight;
                    //oWordApplic.Selection.HeaderFooter.PageNumbers.Item(1).Alignment = Microsoft.Office.Interop.Word.WdPageNumberAlignment.wdAlignPageNumberRight;
                    break;
                case "Left":
                    alignment = Microsoft.Office.Interop.Word.WdPageNumberAlignment.wdAlignPageNumberLeft;
                    oWordApplic.Selection.HeaderFooter.PageNumbers.Add(ref alignment, ref bFirstPage);
                    break;
            }

        }

    }
}

导出Excel实现

1:在项目中Nuget中下载 NPOI工具包,并添加引用

using NPOI;
using NPOI.HPSF;
using NPOI.HSSF;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.POIFS;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.Util;

2:使用ADO.NET连接数据库,获取相关表的数据,SqlDataAdapter 对象FILL给DataTable
在这里插入图片描述

后端代码

   /// <summary>
        /// 加载事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
    
    
            if (!IsPostBack)
            {
    
    
                //获取数据库中相关数据结果集
                DataTable dt = Service.GetDatetable("select * from [dbo].[StudentT]");
                ViewState["dt"] = dt;
                Datapanel.DataSource = dt;
                Datapanel.DataBind();
            }
        }

        /// <summary>
        /// 导出Excel点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ToExcel_Click(object sender, EventArgs e)
        {
    
    
            //调用 ExcelHelp类
            ExcelHelp.ExportByWeb((DataTable)ViewState["dt"], "测试表导出", "报表.xls");
        }

ExcelHelp类

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using NPOI;
using NPOI.HPSF;
using NPOI.HSSF;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.POIFS;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.Util;
namespace Exsercise
{
    
    
    public class ExcelHelp
    {
    
    
        /// <summary>   
        /// DataTable导出到Excel的MemoryStream   
        /// </summary>   
        /// <param name="dtSource">源DataTable</param>   
        /// <param name="strHeaderText">表头文本</param>   
        public static MemoryStream Export(DataTable dtSource, string strHeaderText)
        {
    
    
            HSSFWorkbook workbook = new HSSFWorkbook();
            NPOI.SS.UserModel.ISheet sheet = workbook.CreateSheet();
         

            #region 右击文件 属性信息
            {
    
    
                DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
                dsi.Company = "http://www.yongfa365.com/";
                workbook.DocumentSummaryInformation = dsi;

                SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
                si.Author = ""; //填加xls文件作者信息   
                si.ApplicationName = "NPOI测试程序"; //填加xls文件创建程序信息   
                si.LastAuthor = ""; //填加xls文件最后保存者信息   
                si.Comments = "说明信息"; //填加xls文件作者信息   
                si.Title = "NPOI测试"; //填加xls文件标题信息   
                si.Subject = "NPOI测试Demo";//填加文件主题信息   
                si.CreateDateTime = DateTime.Now;
                workbook.SummaryInformation = si;
            }
            #endregion
            NPOI.SS.UserModel.ICellStyle dateStyle= workbook.CreateCellStyle();
           // HSSFCellStyle dateStyle = workbook.CreateCellStyle();
        

            IDataFormat format = workbook.CreateDataFormat();
            dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");

            //取得列宽   
            int[] arrColWidth = new int[dtSource.Columns.Count];
            foreach (DataColumn item in dtSource.Columns)
            {
    
    
                arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length;
            }
            for (int i = 0; i < dtSource.Rows.Count; i++)
            {
    
    
                for (int j = 0; j < dtSource.Columns.Count; j++)
                {
    
    
                    int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length;
                    if (intTemp > arrColWidth[j])
                    {
    
    
                        arrColWidth[j] = intTemp;
                    }
                }
            }



            int rowIndex = 0;

            foreach (DataRow row in dtSource.Rows)
            {
    
    
                #region 新建表,填充表头,填充列头,样式
                if (rowIndex == 65535 || rowIndex == 0)
                {
    
    
                    if (rowIndex != 0)
                    {
    
    
                        sheet = workbook.CreateSheet();
                    }

                    #region 表头及样式
                    {
    
    

                        IRow headerRow = sheet.CreateRow(0);
                        headerRow.HeightInPoints = 25;
                        headerRow.CreateCell(0).SetCellValue(strHeaderText);
                        ICellStyle headStyle = workbook.CreateCellStyle();
                        // headStyle.Alignment = CellHorizontalAlignment.CENTER;
                        IFont font = workbook.CreateFont();
                        font.FontHeightInPoints = 20;
                        font.Boldweight = 700;
                        headStyle.SetFont(font);

                        headerRow.GetCell(0).CellStyle = headStyle;

                        sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, dtSource.Columns.Count - 1));
                        // headerRow.Dispose();
                    }
                    #endregion


                    #region 列头及样式
                    {
    
    
                        IRow headerRow = sheet.CreateRow(1);


                        ICellStyle headStyle = workbook.CreateCellStyle();
                        // headStyle.Alignment = CellHorizontalAlignment.CENTER;
                        IFont font = workbook.CreateFont();
                        font.FontHeightInPoints = 10;
                        font.Boldweight = 700;
                        headStyle.SetFont(font);


                        foreach (DataColumn column in dtSource.Columns)
                        {
    
    
                            headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
                            headerRow.GetCell(column.Ordinal).CellStyle = headStyle;

                            //设置列宽   
                            sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);

                        }
                        //   headerRow.Dispose();
                    }
                    #endregion

                    rowIndex = 2;
                }
                #endregion


                #region 填充内容
                IRow dataRow = sheet.CreateRow(rowIndex);
                foreach (DataColumn column in dtSource.Columns)
                {
    
    
                    ICell newCell = dataRow.CreateCell(column.Ordinal);

                    string drValue = row[column].ToString();

                    switch (column.DataType.ToString())
                    {
    
    
                        case "System.String"://字符串类型   
                            newCell.SetCellValue(drValue);
                            break;
                        case "System.DateTime"://日期类型   
                            DateTime dateV;
                            DateTime.TryParse(drValue, out dateV);
                            newCell.SetCellValue(dateV);

                            newCell.CellStyle = dateStyle;//格式化显示   
                            break;
                        case "System.Boolean"://布尔型   
                            bool boolV = false;
                            bool.TryParse(drValue, out boolV);
                            newCell.SetCellValue(boolV);
                            break;
                        case "System.Int16"://整型   
                        case "System.Int32":
                        case "System.Int64":
                        case "System.Byte":
                            int intV = 0;
                            int.TryParse(drValue, out intV);
                            newCell.SetCellValue(intV);
                            break;
                        case "System.Decimal"://浮点型   
                        case "System.Double":
                            double doubV = 0;
                            double.TryParse(drValue, out doubV);
                            newCell.SetCellValue(doubV);
                            break;
                        case "System.DBNull"://空值处理   
                            newCell.SetCellValue("");
                            break;
                        default:
                            newCell.SetCellValue("");
                            break;
                    }

                }
                #endregion

                rowIndex++;
            }


            using (MemoryStream ms = new MemoryStream())
            {
    
    
                workbook.Write(ms);
                ms.Flush();
                ms.Position = 0;

                // sheet.Dispose();
                //workbook.Dispose();//一般只用写这一个就OK了,他会遍历并释放所有资源,但当前版本有问题所以只释放sheet   
                return ms;
            }

        }


        /// <summary>   
        /// 用于Web导出   
        /// </summary>   
        /// <param name="dtSource">源DataTable</param>   
        /// <param name="strHeaderText">表头文本</param>   
        /// <param name="strFileName">文件名</param>   
        public static void ExportByWeb(DataTable dtSource, string strHeaderText, string strFileName)
        {
    
    

            HttpContext curContext = HttpContext.Current;
            // 下载于www.51aspx.com
            // 设置编码和附件格式   
            curContext.Response.ContentType = "application/vnd.ms-excel";
            curContext.Response.ContentEncoding = Encoding.UTF8;
            curContext.Response.Charset = "";
            curContext.Response.AppendHeader("Content-Disposition",
                "attachment;filename=" + HttpUtility.UrlEncode(strFileName, Encoding.UTF8));

            curContext.Response.BinaryWrite(Export(dtSource, strHeaderText).GetBuffer());
            curContext.Response.End();

        }


        /// <summary>读取excel   
        /// 默认第一行为标头   
        /// </summary>   
        /// <param name="strFileName">excel文档路径</param>   
        /// <returns></returns>   
        public static DataTable Import(string strFileName)
        {
    
    
            DataTable dt = new DataTable();

            HSSFWorkbook hssfworkbook;
            using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
            {
    
    
                hssfworkbook = new HSSFWorkbook(file);
            }
            ISheet sheet = hssfworkbook.GetSheetAt(0);
            System.Collections.IEnumerator rows = sheet.GetRowEnumerator();

            IRow headerRow = sheet.GetRow(0);
            int cellCount = headerRow.LastCellNum;

            for (int j = 0; j < cellCount; j++)
            {
    
    
                ICell cell = headerRow.GetCell(j);
                dt.Columns.Add(cell.ToString());
            }

            for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
            {
    
    
                IRow row = sheet.GetRow(i);
                DataRow dataRow = dt.NewRow();

                for (int j = row.FirstCellNum; j < cellCount; j++)
                {
    
    
                    if (row.GetCell(j) != null)
                        dataRow[j] = row.GetCell(j).ToString();
                }

                dt.Rows.Add(dataRow);
            }
            return dt;
        }

    }
}

导出效果图

在这里插入图片描述
好了,今天就先介绍到这里,谢谢大家。欢迎指出不足,诚恳接受批评。有问题,可以留言。

猜你喜欢

转载自blog.csdn.net/WenRouDG/article/details/108113082
今日推荐