很多的软件项目几乎都包含着对文档的操作,前面已经介绍过两款操作文档的组件,现在介绍一款文档操作的组件NPOI。

NPOI可以生成没有安装在您的服务器上的Microsoft Office套件的Excel报表,并且在后台调用Microsoft Excel ActiveX更有效率;从Office文档中提取文本,以帮助您实现全文索引功能(大多数时候,此功能用于创建搜索引擎); 从Office文档提取图像; 生成包含公式的Excel工作表。

一.NPOI组件概述:

NPOI是完全免费使用; 涵盖Excel的大多数功能(单元格样式,数据格式,公式等);支持xls,xlsx,docx;设计为面向接口(看看NPOI.SS命名空间);支持不仅导出而且导入; .Net 2.0甚至为xlsx和docx(虽然我们也支持.NET 4.0); 来自世界各地的成功案例;巨大的基本例子;对隔离存储没有依赖。

以上是NPOI的优点,其他一些优点可以不用太在意,估计很多人对“支持xls,xlsx,docx”这一特点感觉有些惊讶,因为在很多人的印象里面NPOI就是对Excel进行相关的操作,但是在这里突然看到了对docx也可以操作,这一特点可能让很多人感到欣喜,因为NPOI的的确确是一个很不错的组件,用过的人都说好,我也不例外。

NPOI的运行要求:VS2010与.NET 4.0运行时;VS2005或VS2008与.NET 2.0运行时(SP1);vs2003与.NET 1.1;Mono;ASP.NET中的中等信任环境。

二.NPOI核心类和方法解析:

以上是对NPOI的相关背景和使用环境做了一个简单的介绍,接下来我具体的看一下NPOI的一些核心类和方法,由于下载的是DLL文件,还是采用.NET Reflector对DLL文件进行反编译,以此查看源代码。

如果需要具体的了解NPOI可以直接访问:http://npoi.codeplex.com/SourceControl/latest,提供了NPOI的源码和一些demo,由于本溪介绍的重点是NPOI对Excel的操作,所以下面的类和实例主要是对操作Excel的介绍,如果需要对docx的操作,可以具体查看相应的类demo。

免费高效实用的.NET操作Excel组件NPOI(.NET组件介绍之六)免费高效实用的.NET操作Excel组件NPOI(.NET组件介绍之六)免费高效实用的.NET操作Excel组件NPOI(.NET组件介绍之六)免费高效实用的.NET操作Excel组件NPOI(.NET组件介绍之六)免费高效实用的.NET操作Excel组件NPOI(.NET组件介绍之六)

1.XSSFWorkbook类CreateSheet():创建表。

public ISheet CreateSheet(string sheetname)<br/>
{<br/>
    if (sheetname == null)<br/>
    {<br/>
        throw new ArgumentException("sheetName must not be null");<br/>
    }<br/>
    if (this.ContainsSheet(sheetname, this.sheets.Count))<br/>
    {<br/>
        throw new ArgumentException("The workbook already contains a sheet of this name");<br/>
    }<br/>
    if (sheetname.Length > 0x1f)<br/>
    {<br/>
        sheetname = sheetname.Substring(, 0x1f);<br/>
    }<br/>
    WorkbookUtil.ValidateSheetName(sheetname);<br/>
    CT_Sheet sheet = this.AddSheet(sheetname);<br/>
    int index = ;<br/>
    foreach (XSSFSheet sheet2 in this.sheets)<br/>
    {<br/>
        index = (int) Math.Max((long) (sheet2.sheet.sheetId + ), (long) index);<br/>
    }<br/>
Label_0099:<br/>
    foreach (XSSFSheet sheet3 in this.sheets)<br/>
    {<br/>
        index = (int) Math.Max((long) (sheet3.sheet.sheetId + ), (long) index);<br/>
    }<br/>
    string fileName = XSSFRelation.WORKSHEET.GetFileName(index);<br/>
    foreach (POIXMLDocumentPart part in base.GetRelations())<br/>
    {<br/>
        if ((part.GetPackagePart() != null) && fileName.Equals(part.GetPackagePart().PartName.Name))<br/>
        {<br/>
            index++;<br/>
            goto Label_0099;<br/>
        }<br/>
    }<br/>
    XSSFSheet item = (XSSFSheet) base.CreateRelationship(XSSFRelation.WORKSHEET, XSSFFactory.GetInstance(), index);<br/>
    item.sheet = sheet;<br/>
    sheet.id = item.GetPackageRelationship().Id;<br/>
    sheet.sheetId = (uint) index;<br/>
    if (this.sheets.Count == )<br/>
    {<br/>
        item.IsSelected = true;<br/>
    }<br/>
    this.sheets.Add(item);<br/>
    return item;<br/>
}

2.XSSFSheet类Write():将文件流写入到excel。

internal virtual void Write(Stream stream)<br/>
{<br/>
    bool flag = false;<br/>
    if (this.worksheet.sizeOfColsArray() == )<br/>
    {<br/>
        CT_Cols colsArray = this.worksheet.GetColsArray();<br/>
        if (colsArray.sizeOfColArray() == )<br/>
        {<br/>
            flag = true;<br/>
            this.worksheet.SetColsArray(null);<br/>
        }<br/>
        else<br/>
        {<br/>
            this.SetColWidthAttribute(colsArray);<br/>
        }<br/>
    }<br/>
    if (this.hyperlinks.Count > )<br/>
    {<br/>
        if (this.worksheet.hyperlinks == null)<br/>
        {<br/>
            this.worksheet.AddNewHyperlinks();<br/>
        }<br/>
        CT_Hyperlink[] array = new CT_Hyperlink[this.hyperlinks.Count];<br/>
        for (int i = ; i < array.Length; i++)<br/>
        {<br/>
            XSSFHyperlink hyperlink = this.hyperlinks[i];<br/>
            hyperlink.GenerateRelationIfNeeded(base.GetPackagePart());<br/>
            array[i] = hyperlink.GetCTHyperlink();<br/>
        }<br/>
        this.worksheet.hyperlinks.SetHyperlinkArray(array);<br/>
    }<br/>
    foreach (XSSFRow row in this._rows.Values)<br/>
    {<br/>
        row.OnDocumentWrite();<br/>
    }<br/>
    Dictionary<string, string> dictionary = new Dictionary<string, string>();<br/>
    dictionary[ST_RelationshipId.NamespaceURI] = "r";<br/>
    new WorksheetDocument(this.worksheet).Save(stream);<br/>
    if (flag)<br/>
    {<br/>
        this.worksheet.AddNewCols();<br/>
    }<br/>
}<br/>

3.XSSFSheet类CreateRow():创建行。

public virtual IRow CreateRow(int rownum)<br/>
{<br/>
    CT_Row cTRow;<br/>
    XSSFRow row2 = this._rows.ContainsKey(rownum) ? this._rows[rownum] : null;<br/>
    if (row2 != null)<br/>
    {<br/>
        cTRow = row2.GetCTRow();<br/>
        cTRow.Set(new CT_Row());<br/>
    }<br/>
    else if ((this._rows.Count == ) || (rownum > this.GetLastKey(this._rows.Keys)))<br/>
    {<br/>
        cTRow = this.worksheet.sheetData.AddNewRow();<br/>
    }<br/>
    else<br/>
    {<br/>
        int count = this.HeadMap(this._rows, rownum).Count;<br/>
        cTRow = this.worksheet.sheetData.InsertNewRow(count);<br/>
    }<br/>
    XSSFRow row3 = new XSSFRow(cTRow, this) {<br/>
        RowNum = rownum<br/>
    };<br/>
    this._rows[rownum] = row3;<br/>
    return row3;<br/>
}

4.XSSFWorkbook类GetSheet:获取表。

public ISheet GetSheet(string name)<br/>
{<br/>
    foreach (XSSFSheet sheet in this.sheets)<br/>
    {<br/>
        if (name.Equals(sheet.SheetName, StringComparison.InvariantCultureIgnoreCase))<br/>
        {<br/>
            return sheet;<br/>
        }<br/>
    }<br/>
    return null;<br/>
}

5.WorkbookFactory类:

  public class PropertySetFactory<br/>
  {<br/>
    public static PropertySet Create(DirectoryEntry dir, string name);<br/>
    public static PropertySet Create(Stream stream);<br/>
    public static SummaryInformation CreateSummaryInformation();<br/>
    public static DocumentSummaryInformation CreateDocumentSummaryInformation();<br/>
  }

6.DocumentSummaryInformation:

[Serializable]<br/>
public class DocumentSummaryInformation : SpecialPropertySet<br/>
{<br/>
    // Fields<br/>
    public const string DEFAULT_STREAM_NAME = "\x0005DocumentSummaryInformation";

    // Methods<br/>
    public DocumentSummaryInformation(PropertySet ps);<br/>
    private void EnsureSection2();<br/>
    public void RemoveByteCount();<br/>
    public void RemoveCategory();<br/>
    public void RemoveCompany();<br/>
    public void RemoveCustomProperties();<br/>
    public void RemoveDocparts();<br/>
    public void RemoveHeadingPair();<br/>
    public void RemoveHiddenCount();<br/>
    public void RemoveLineCount();<br/>
    public void RemoveLinksDirty();<br/>
    public void RemoveManager();<br/>
    public void RemoveMMClipCount();<br/>
    public void RemoveNoteCount();<br/>
    public void RemoveParCount();<br/>
    public void RemovePresentationFormat();<br/>
    public void RemoveScale();<br/>
    public void RemoveSlideCount();

    // Properties<br/>
    public int ByteCount { get; set; }<br/>
    public string Category { get; set; }<br/>
    public string Company { get; set; }<br/>
    public CustomProperties CustomProperties { get; set; }<br/>
    public byte[] Docparts { get; set; }<br/>
    public byte[] HeadingPair { get; set; }<br/>
    public int HiddenCount { get; set; }<br/>
    public int LineCount { get; set; }<br/>
    public bool LinksDirty { get; set; }<br/>
    public string Manager { get; set; }<br/>
    public int MMClipCount { get; set; }<br/>
    public int NoteCount { get; set; }<br/>
    public int ParCount { get; set; }<br/>
    public string PresentationFormat { get; set; }<br/>
    public override PropertyIDMap PropertySetIDMap { get; }<br/>
    public bool Scale { get; set; }<br/>
    public int SlideCount { get; set; }<br/>
}

具体方法:<br/>
private void EnsureSection2()<br/>
{<br/>
    if (this.SectionCount < )<br/>
    {<br/>
        MutableSection section = new MutableSection();<br/>
        section.SetFormatID(SectionIDMap.DOCUMENT_SUMMARY_INFORMATION_ID2);<br/>
        this.AddSection(section);<br/>
    }<br/>
}

以上只是对部分的类和方法做了简单的说明,需要了解更多的内容,可以进入官网下载源码,或者使用软件查看DLL文件。

三.NPOI操作实例:

1.枚举(Excel单元格数据类型):

    /// <summary><br/>
    /// 枚举(Excel单元格数据类型)<br/>
    /// </summary><br/>
    public enum NpoiDataType<br/>
    {<br/>
        /// <summary><br/>
        /// 字符串类型-值为1<br/>
        /// </summary><br/>
        String,<br/>
        /// <summary><br/>
        /// 布尔类型-值为2<br/>
        /// </summary><br/>
        Bool,<br/>
        /// <summary><br/>
        /// 时间类型-值为3<br/>
        /// </summary><br/>
        Datetime,<br/>
        /// <summary><br/>
        /// 数字类型-值为4<br/>
        /// </summary><br/>
        Numeric,<br/>
        /// <summary><br/>
        /// 复杂文本类型-值为5<br/>
        /// </summary><br/>
        Richtext,<br/>
        /// <summary><br/>
        /// 空白<br/>
        /// </summary><br/>
        Blank,<br/>
        /// <summary><br/>
        /// 错误<br/>
        /// </summary><br/>
        Error<br/>
    }

2. 将DataTable数据导入到excel中:

        /// <summary><br/>
        /// 将DataTable数据导入到excel中<br/>
        /// </summary><br/>
        /// <param name="data">要导入的数据</param><br/>
        /// <param name="isColumnWritten">DataTable的列名是否要导入</param><br/>
        /// <param name="sheetName">要导入的excel的sheet的名称</param><br/>
        /// <param name="fileName">文件夹路径</param><br/>
        /// <returns>导入数据行数(包含列名那一行)</returns><br/>
        public static int DataTableToExcel(DataTable data, string sheetName, bool isColumnWritten, string fileName)<br/>
        {<br/>
            if (data == null)<br/>
            {<br/>
                throw new ArgumentNullException("data");<br/>
            }<br/>
            if (string.IsNullOrEmpty(sheetName))<br/>
            {<br/>
                throw new ArgumentNullException(sheetName);<br/>
            }<br/>
            if (string.IsNullOrEmpty(fileName))<br/>
            {<br/>
                throw new ArgumentNullException(fileName);<br/>
            }<br/>
            IWorkbook workbook = null;<br/>
            if (fileName.IndexOf(".xlsx", StringComparison.Ordinal) > )<br/>
            {<br/>
                workbook = new XSSFWorkbook();<br/>
            }<br/>
            else if (fileName.IndexOf(".xls", StringComparison.Ordinal) > )<br/>
            {<br/>
                workbook = new HSSFWorkbook();<br/>
            }

            FileStream fs = null;<br/>
            try<br/>
            {<br/>
                fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);<br/>
                ISheet sheet;<br/>
                if (workbook != null)<br/>
                {<br/>
                    sheet = workbook.CreateSheet(sheetName);<br/>
                }<br/>
                else<br/>
                {<br/>
                    return -;<br/>
                }

                int j;<br/>
                int count;<br/>
                //写入DataTable的列名,写入单元格中<br/>
                if (isColumnWritten)<br/>
                {<br/>
                    var row = sheet.CreateRow();<br/>
                    for (j = ; j < data.Columns.Count; ++j)<br/>
                    {<br/>
                        row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);<br/>
                    }<br/>
                    count = ;<br/>
                }<br/>
                else<br/>
                {<br/>
                    count = ;<br/>
                }<br/>
                //遍历循环datatable具体数据项<br/>
                int i;<br/>
                for (i = ; i < data.Rows.Count; ++i)<br/>
                {<br/>
                    var row = sheet.CreateRow(count);<br/>
                    for (j = ; j < data.Columns.Count; ++j)<br/>
                    {<br/>
                        row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());<br/>
                    }<br/>
                    ++count;<br/>
                }<br/>
                //将文件流写入到excel<br/>
                workbook.Write(fs);<br/>
                return count;<br/>
            }<br/>
            catch (IOException ioex)<br/>
            {<br/>
                throw new IOException(ioex.Message);<br/>
            }<br/>
            catch (Exception ex)<br/>
            {<br/>
                throw new Exception(ex.Message);<br/>
            }<br/>
            finally<br/>
            {<br/>
                if (fs != null)<br/>
                {<br/>
                    fs.Close();<br/>
                }<br/>
            }<br/>
        }

3.将excel中的数据导入到DataTable中:

        /// <summary><br/>
        /// 将excel中的数据导入到DataTable中<br/>
        /// </summary><br/>
        /// <param name="sheetName">excel工作薄sheet的名称</param><br/>
        /// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param><br/>
        /// <param name="fileName">文件路径</param><br/>
        /// <returns>返回的DataTable</returns><br/>
        public static DataTable ExcelToDataTable(string sheetName, bool isFirstRowColumn, string fileName)<br/>
        {<br/>
            if (string.IsNullOrEmpty(sheetName))<br/>
            {<br/>
                throw new ArgumentNullException(sheetName);<br/>
            }<br/>
            if (string.IsNullOrEmpty(fileName))<br/>
            {<br/>
                throw new ArgumentNullException(fileName);<br/>
            }<br/>
            var data = new DataTable();<br/>
            IWorkbook workbook = null;<br/>
            FileStream fs = null;<br/>
            try<br/>
            {<br/>
                fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);<br/>
                if (fileName.IndexOf(".xlsx", StringComparison.Ordinal) > )<br/>
                {<br/>
                    workbook = new XSSFWorkbook(fs);<br/>
                }<br/>
                else if (fileName.IndexOf(".xls", StringComparison.Ordinal) > )<br/>
                {<br/>
                    workbook = new HSSFWorkbook(fs);<br/>
                }

                ISheet sheet = null;<br/>
                if (workbook != null)<br/>
                {<br/>
                    //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet<br/>
                    sheet = workbook.GetSheet(sheetName) ?? workbook.GetSheetAt();<br/>
                }<br/>
                if (sheet == null) return data;<br/>
                var firstRow = sheet.GetRow();<br/>
                //一行最后一个cell的编号 即总的列数<br/>
                int cellCount = firstRow.LastCellNum;<br/>
                int startRow;<br/>
                if (isFirstRowColumn)<br/>
                {<br/>
                    for (int i = firstRow.FirstCellNum; i < cellCount; ++i)<br/>
                    {<br/>
                        var cell = firstRow.GetCell(i);<br/>
                        var cellValue = cell.StringCellValue;<br/>
                        if (cellValue == null) continue;<br/>
                        var column = new DataColumn(cellValue);<br/>
                        data.Columns.Add(column);<br/>
                    }<br/>
                    startRow = sheet.FirstRowNum + ;<br/>
                }<br/>
                else<br/>
                {<br/>
                    startRow = sheet.FirstRowNum;<br/>
                }<br/>
                //最后一列的标号<br/>
                var rowCount = sheet.LastRowNum;<br/>
                for (var i = startRow; i <= rowCount; ++i)<br/>
                {<br/>
                    var row = sheet.GetRow(i);<br/>
                    //没有数据的行默认是null<br/>
                    if (row == null) continue;<br/>
                    var dataRow = data.NewRow();<br/>
                    for (int j = row.FirstCellNum; j < cellCount; ++j)<br/>
                    {<br/>
                        //同理,没有数据的单元格都默认是null<br/>
                        if (row.GetCell(j) != null)<br/>
                            dataRow[j] = row.GetCell(j).ToString();<br/>
                    }<br/>
                    data.Rows.Add(dataRow);<br/>
                }

                return data;<br/>
            }<br/>
            catch (IOException ioex)<br/>
            {<br/>
                throw new IOException(ioex.Message);<br/>
            }<br/>
            catch (Exception ex)<br/>
            {<br/>
                throw new Exception(ex.Message);<br/>
            }<br/>
            finally<br/>
            {<br/>
                if (fs != null)<br/>
                {<br/>
                    fs.Close();<br/>
                }<br/>
            }<br/>
        }

4.读取Excel文件内容转换为DataSet:

       /// <summary><br/>
        /// 读取Excel文件内容转换为DataSet,列名依次为 "c0"……c[columnlength-1]<br/>
        /// </summary><br/>
        /// <param name="fileName">文件绝对路径</param><br/>
        /// <param name="startRow">数据开始行数(1为第一行)</param><br/>
        /// <param name="columnDataType">每列的数据类型</param><br/>
        /// <returns></returns><br/>
        public static DataSet ReadExcel(string fileName, int startRow, params NpoiDataType[] columnDataType)<br/>
        {<br/>
            var ds = new DataSet("ds");<br/>
            var dt = new DataTable("dt");<br/>
            var sb = new StringBuilder();<br/>
            using (var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read))<br/>
            {<br/>
                //使用接口,自动识别excel2003/2007格式<br/>
                var workbook = WorkbookFactory.Create(stream);<br/>
                //得到里面第一个sheet<br/>
                var sheet = workbook.GetSheetAt();<br/>
                int j;<br/>
                IRow row;<br/>
                //ColumnDataType赋值<br/>
                if (columnDataType.Length <= )<br/>
                {<br/>
                    //得到第i行<br/>
                    row = sheet.GetRow(startRow - );<br/>
                    columnDataType = new NpoiDataType[row.LastCellNum];<br/>
                    for (var i = ; i < row.LastCellNum; i++)<br/>
                    {<br/>
                        var hs = row.GetCell(i);<br/>
                        columnDataType[i] = GetCellDataType(hs);<br/>
                    }<br/>
                }<br/>
                for (j = ; j < columnDataType.Length; j++)<br/>
                {<br/>
                    var tp = GetDataTableType(columnDataType[j]);<br/>
                    dt.Columns.Add("c" + j, tp);<br/>
                }<br/>
                for (var i = startRow - ; i <= sheet.PhysicalNumberOfRows; i++)<br/>
                {<br/>
                    //得到第i行<br/>
                    row = sheet.GetRow(i);<br/>
                    if (row == null) continue;<br/>
                    try<br/>
                    {<br/>
                        var dr = dt.NewRow();

                        for (j = ; j < columnDataType.Length; j++)<br/>
                        {<br/>
                            dr["c" + j] = GetCellData(columnDataType[j], row, j);<br/>
                        }<br/>
                        dt.Rows.Add(dr);<br/>
                    }<br/>
                    catch (Exception er)<br/>
                    {<br/>
                        sb.Append(string.Format("第{0}行出错:{1}\r\n", i + , er.Message));<br/>
                    }<br/>
                }<br/>
                ds.Tables.Add(dt);<br/>
            }<br/>
            if (ds.Tables[].Rows.Count ==  && sb.ToString() != "") throw new Exception(sb.ToString());<br/>
            return ds;<br/>
        }

5.从DataSet导出到2003:

        /// <summary><br/>
        /// 从DataSet导出到MemoryStream流2003<br/>
        /// </summary><br/>
        /// <param name="saveFileName">文件保存路径</param><br/>
        /// <param name="sheetName">Excel文件中的Sheet名称</param><br/>
        /// <param name="ds">存储数据的DataSet</param><br/>
        /// <param name="startRow">从哪一行开始写入,从0开始</param><br/>
        /// <param name="datatypes">DataSet中的各列对应的数据类型</param><br/>
        public static bool CreateExcel2003(string saveFileName, string sheetName, DataSet ds, int startRow, params NpoiDataType[] datatypes)<br/>
        {<br/>
            try<br/>
            {<br/>
                if (startRow < ) startRow = ;<br/>
                var wb = new HSSFWorkbook();<br/>
                var dsi = PropertySetFactory.CreateDocumentSummaryInformation();<br/>
                dsi.Company = "pkm";<br/>
                var si = PropertySetFactory.CreateSummaryInformation();<br/>
                si.Title =<br/>
                si.Subject = "automatic genereted document";<br/>
                si.Author = "pkm";<br/>
                wb.DocumentSummaryInformation = dsi;<br/>
                wb.SummaryInformation = si;<br/>
                var sheet = wb.CreateSheet(sheetName);<br/>
                //sheet.SetColumnWidth(0, 50 * 256);<br/>
                //sheet.SetColumnWidth(1, 100 * 256);<br/>
                ICell cell;<br/>
                int j;<br/>
                var maxLength = ;<br/>
                var curLength = ;<br/>
                object columnValue;<br/>
                var dt = ds.Tables[];<br/>
                if (datatypes.Length < dt.Columns.Count)<br/>
                {<br/>
                    datatypes = new NpoiDataType[dt.Columns.Count];<br/>
                    for (var i = ; i < dt.Columns.Count; i++)<br/>
                    {<br/>
                        var dtcolumntype = dt.Columns[i].DataType.Name.ToLower();<br/>
                        switch (dtcolumntype)<br/>
                        {<br/>
                            case "string":<br/>
                                datatypes[i] = NpoiDataType.String;<br/>
                                break;<br/>
                            case "datetime":<br/>
                                datatypes[i] = NpoiDataType.Datetime;<br/>
                                break;<br/>
                            case "boolean":<br/>
                                datatypes[i] = NpoiDataType.Bool;<br/>
                                break;<br/>
                            case "double":<br/>
                                datatypes[i] = NpoiDataType.Numeric;<br/>
                                break;<br/>
                            default:<br/>
                                datatypes[i] = NpoiDataType.String;<br/>
                                break;<br/>
                        }<br/>
                    }<br/>
                }

                // 创建表头<br/>
                var row = sheet.CreateRow();<br/>
                //样式<br/>
                var style1 = wb.CreateCellStyle();<br/>
                //字体<br/>
                var font1 = wb.CreateFont();<br/>
                //字体颜色<br/>
                font1.Color = HSSFColor.White.Index;<br/>
                //字体加粗样式<br/>
                font1.Boldweight = (short)FontBoldWeight.Bold;<br/>
                //style1.FillBackgroundColor = HSSFColor.WHITE.index;<br/>
                style1.FillForegroundColor = HSSFColor.Green.Index;<br/>
                //GetXLColour(wb, LevelOneColor);// 设置图案色<br/>
                //GetXLColour(wb, LevelOneColor);// 设置背景色<br/>
                style1.FillPattern = FillPattern.SolidForeground;<br/>
                //样式里的字体设置具体的字体样式<br/>
                style1.SetFont(font1);<br/>
                //文字水平对齐方式<br/>
                style1.Alignment = HorizontalAlignment.Center;<br/>
                //文字垂直对齐方式<br/>
                style1.VerticalAlignment = VerticalAlignment.Center;<br/>
                row.HeightInPoints = ;<br/>
                for (j = ; j < dt.Columns.Count; j++)<br/>
                {<br/>
                    columnValue = dt.Columns[j].ColumnName;<br/>
                    curLength = Encoding.Default.GetByteCount(columnValue.ToString());<br/>
                    maxLength = (maxLength < curLength ? curLength : maxLength);<br/>
                    var colounwidth =  * maxLength;<br/>
                    sheet.SetColumnWidth(j, colounwidth);<br/>
                    try<br/>
                    {<br/>
                        //创建第0行的第j列<br/>
                        cell = row.CreateCell(j);<br/>
                        //单元格式设置样式<br/>
                        cell.CellStyle = style1;

                        try<br/>
                        {<br/>
                            cell.SetCellType(CellType.String);<br/>
                            cell.SetCellValue(columnValue.ToString());<br/>
                        }<br/>
                        catch (Exception ex)<br/>
                        {<br/>
                            throw new Exception(ex.Message);<br/>
                        }

                    }<br/>
                    catch (Exception ex)<br/>
                    {<br/>
                        throw new Exception(ex.Message);<br/>
                    }<br/>
                }<br/>
                // 创建每一行<br/>
                for (var i = startRow; i < ds.Tables[].Rows.Count; i++)<br/>
                {<br/>
                    var dr = ds.Tables[].Rows[i];<br/>
                    //创建第i行<br/>
                    row = sheet.CreateRow(i + );<br/>
                    for (j = ; j < dt.Columns.Count; j++)<br/>
                    {<br/>
                        columnValue = dr[j];<br/>
                        curLength = Encoding.Default.GetByteCount(columnValue.ToString());<br/>
                        maxLength = (maxLength < curLength ? curLength : maxLength);<br/>
                        var colounwidth =  * maxLength;<br/>
                        sheet.SetColumnWidth(j, colounwidth);<br/>
                        try<br/>
                        {<br/>
                            //创建第i行的第j列<br/>
                            cell = row.CreateCell(j);<br/>
                            // 插入第j列的数据<br/>
                            try<br/>
                            {<br/>
                                var dtype = datatypes[j];<br/>
                                switch (dtype)<br/>
                                {<br/>
                                    case NpoiDataType.String:<br/>
                                        {<br/>
                                            cell.SetCellType(CellType.Numeric);<br/>
                                            cell.SetCellValue(columnValue.ToString());<br/>
                                        }<br/>
                                        break;<br/>
                                    case NpoiDataType.Datetime:<br/>
                                        {<br/>
                                            cell.SetCellType(CellType.Numeric);<br/>
                                            cell.SetCellValue(columnValue.ToString());<br/>
                                        }<br/>
                                        break;<br/>
                                    case NpoiDataType.Numeric:<br/>
                                        {<br/>
                                            cell.SetCellType(CellType.Numeric);<br/>
                                            cell.SetCellValue(Convert.ToDouble(columnValue));<br/>
                                        }<br/>
                                        break;<br/>
                                    case NpoiDataType.Bool:<br/>
                                        {<br/>
                                            cell.SetCellType(CellType.Numeric);<br/>
                                            cell.SetCellValue(Convert.ToBoolean(columnValue));<br/>
                                        }<br/>
                                        break;<br/>
                                    case NpoiDataType.Richtext:<br/>
                                        {<br/>
                                            cell.SetCellType(CellType.Numeric);<br/>
                                            cell.SetCellValue(columnValue.ToString());<br/>
                                        }<br/>
                                        break;<br/>
                                }<br/>
                            }<br/>
                            catch (Exception ex)<br/>
                            {<br/>
                                cell.SetCellType(CellType.Numeric);<br/>
                                cell.SetCellValue(columnValue.ToString());<br/>
                                throw new Exception(ex.Message);<br/>
                            }<br/>
                        }<br/>
                        catch (Exception ex)<br/>
                        {<br/>
                            throw new Exception(ex.Message);<br/>
                        }<br/>
                    }<br/>
                }<br/>
                //生成文件在服务器上<br/>
                using (var fs = new FileStream(saveFileName, FileMode.OpenOrCreate, FileAccess.Write))<br/>
                {<br/>
                    wb.Write(fs);<br/>
                }

                return true;<br/>
            }<br/>
            catch (Exception er)<br/>
            {<br/>
                throw new Exception(er.Message);<br/>
            }

        }

6.从DataSet导出到MemoryStream流2007:

       /// <summary><br/>
        /// 从DataSet导出到MemoryStream流2007<br/>
        /// </summary><br/>
        /// <param name="saveFileName">文件保存路径</param><br/>
        /// <param name="sheetName">Excel文件中的Sheet名称</param><br/>
        /// <param name="ds">存储数据的DataSet</param><br/>
        /// <param name="startRow">从哪一行开始写入,从0开始</param><br/>
        /// <param name="datatypes">DataSet中的各列对应的数据类型</param><br/>
        public static bool CreateExcel2007(string saveFileName, string sheetName, DataSet ds, int startRow, params NpoiDataType[] datatypes)<br/>
        {<br/>
            try<br/>
            {<br/>
                if (startRow < ) startRow = ;<br/>
                var wb = new XSSFWorkbook();<br/>
                var sheet = wb.CreateSheet(sheetName);<br/>
                ICell cell;<br/>
                int j;<br/>
                var maxLength = ;<br/>
                int curLength;<br/>
                object columnValue;<br/>
                var dt = ds.Tables[];<br/>
                if (datatypes.Length < dt.Columns.Count)<br/>
                {<br/>
                    datatypes = new NpoiDataType[dt.Columns.Count];<br/>
                    for (var i = ; i < dt.Columns.Count; i++)<br/>
                    {<br/>
                        var dtcolumntype = dt.Columns[i].DataType.Name.ToLower();<br/>
                        switch (dtcolumntype)<br/>
                        {<br/>
                            case "string":<br/>
                                datatypes[i] = NpoiDataType.String;<br/>
                                break;<br/>
                            case "datetime":<br/>
                                datatypes[i] = NpoiDataType.Datetime;<br/>
                                break;<br/>
                            case "boolean":<br/>
                                datatypes[i] = NpoiDataType.Bool;<br/>
                                break;<br/>
                            case "double":<br/>
                                datatypes[i] = NpoiDataType.Numeric;<br/>
                                break;<br/>
                            default:<br/>
                                datatypes[i] = NpoiDataType.String;<br/>
                                break;<br/>
                        }<br/>
                    }<br/>
                }<br/>
                //创建表头<br/>
                var row = sheet.CreateRow();<br/>
                //样式<br/>
                var style1 = wb.CreateCellStyle();<br/>
                //字体<br/>
                var font1 = wb.CreateFont();<br/>
                //字体颜色<br/>
                font1.Color = HSSFColor.White.Index;<br/>
                //字体加粗样式<br/>
                font1.Boldweight = (short)FontBoldWeight.Bold;<br/>
                //style1.FillBackgroundColor = HSSFColor.WHITE.index;<br/>
                //GetXLColour(wb, LevelOneColor);<br/>
                // 设置图案色<br/>
                style1.FillForegroundColor = HSSFColor.Green.Index;<br/>
                //GetXLColour(wb, LevelOneColor);// 设置背景色<br/>
                style1.FillPattern = FillPattern.SolidForeground;<br/>
                //样式里的字体设置具体的字体样式<br/>
                style1.SetFont(font1);<br/>
                //文字水平对齐方式<br/>
                style1.Alignment = HorizontalAlignment.Center;<br/>
                //文字垂直对齐方式<br/>
                style1.VerticalAlignment = VerticalAlignment.Center;<br/>
                row.HeightInPoints = ;<br/>
                for (j = ; j < dt.Columns.Count; j++)<br/>
                {<br/>
                    columnValue = dt.Columns[j].ColumnName;<br/>
                    curLength = Encoding.Default.GetByteCount(columnValue.ToString());<br/>
                    maxLength = (maxLength < curLength ? curLength : maxLength);<br/>
                    var colounwidth =  * maxLength;<br/>
                    sheet.SetColumnWidth(j, colounwidth);<br/>
                    try<br/>
                    {<br/>
                        //创建第0行的第j列<br/>
                        cell = row.CreateCell(j);<br/>
                        //单元格式设置样式<br/>
                        cell.CellStyle = style1;

                        try<br/>
                        {<br/>
                            cell.SetCellValue(columnValue.ToString());<br/>
                        }<br/>
                        catch (Exception ex)<br/>
                        {<br/>
                            throw new Exception(ex.Message);<br/>
                        }

                    }<br/>
                    catch (Exception ex)<br/>
                    {<br/>
                        throw new Exception(ex.Message);<br/>
                    }<br/>
                }<br/>
                // 创建每一行<br/>
                for (var i = startRow; i < ds.Tables[].Rows.Count; i++)<br/>
                {<br/>
                    var dr = ds.Tables[].Rows[i];<br/>
                    //创建第i行<br/>
                    row = sheet.CreateRow(i + );<br/>
                    for (j = ; j < dt.Columns.Count; j++)<br/>
                    {<br/>
                        columnValue = dr[j];<br/>
                        curLength = Encoding.Default.GetByteCount(columnValue.ToString());<br/>
                        maxLength = (maxLength < curLength ? curLength : maxLength);<br/>
                        var colounwidth =  * maxLength;<br/>
                        sheet.SetColumnWidth(j, colounwidth);<br/>
                        try<br/>
                        {<br/>
                            //创建第i行的第j列<br/>
                            cell = row.CreateCell(j);<br/>
                            // 插入第j列的数据<br/>
                            try<br/>
                            {<br/>
                                var dtype = datatypes[j];<br/>
                                switch (dtype)<br/>
                                {<br/>
                                    case NpoiDataType.String:<br/>
                                        {<br/>
                                            cell.SetCellValue(columnValue.ToString());<br/>
                                        }<br/>
                                        break;<br/>
                                    case NpoiDataType.Datetime:<br/>
                                        {<br/>
                                            cell.SetCellValue(columnValue.ToString());<br/>
                                        }<br/>
                                        break;<br/>
                                    case NpoiDataType.Numeric:<br/>
                                        {<br/>
                                            cell.SetCellValue(Convert.ToDouble(columnValue));<br/>
                                        }<br/>
                                        break;<br/>
                                    case NpoiDataType.Bool:<br/>
                                        {<br/>
                                            cell.SetCellValue(Convert.ToBoolean(columnValue));<br/>
                                        }<br/>
                                        break;<br/>
                                    case NpoiDataType.Richtext:<br/>
                                        {<br/>
                                            cell.SetCellValue(columnValue.ToString());<br/>
                                        }<br/>
                                        break;<br/>
                                }<br/>
                            }<br/>
                            catch (Exception ex)<br/>
                            {<br/>
                                cell.SetCellValue(columnValue.ToString());<br/>
                                throw new Exception(ex.Message);<br/>
                            }<br/>
                        }<br/>
                        catch (Exception ex)<br/>
                        {<br/>
                            throw new Exception(ex.Message);<br/>
                        }<br/>
                    }<br/>
                }<br/>
                //生成文件在服务器上<br/>
                using (var fs = new FileStream(saveFileName, FileMode.OpenOrCreate, FileAccess.Write))<br/>
                {<br/>
                    wb.Write(fs);<br/>
                }<br/>
                return true;<br/>
            }<br/>
            catch (Exception er)<br/>
            {<br/>
                throw new Exception(er.Message);<br/>
            }

        }

7.读Excel-根据NpoiDataType创建的DataTable列的数据类型:

        /// <summary><br/>
        /// 读Excel-根据NpoiDataType创建的DataTable列的数据类型<br/>
        /// </summary><br/>
        /// <param name="datatype"></param><br/>
        /// <returns></returns><br/>
        private static Type GetDataTableType(NpoiDataType datatype)<br/>
        {<br/>
            var tp = typeof(string);<br/>
            switch (datatype)<br/>
            {<br/>
                case NpoiDataType.Bool:<br/>
                    tp = typeof(bool);<br/>
                    break;<br/>
                case NpoiDataType.Datetime:<br/>
                    tp = typeof(DateTime);<br/>
                    break;<br/>
                case NpoiDataType.Numeric:<br/>
                    tp = typeof(double);<br/>
                    break;<br/>
                case NpoiDataType.Error:<br/>
                    tp = typeof(string);<br/>
                    break;<br/>
                case NpoiDataType.Blank:<br/>
                    tp = typeof(string);<br/>
                    break;<br/>
            }<br/>
            return tp;<br/>
        }

        /// <summary><br/>
        /// 读Excel-得到不同数据类型单元格的数据<br/>
        /// </summary><br/>
        /// <param name="datatype">数据类型</param><br/>
        /// <param name="row">数据中的一行</param><br/>
        /// <param name="column">哪列</param><br/>
        /// <returns></returns><br/>
        private static object GetCellData(NpoiDataType datatype, IRow row, int column)<br/>
        {<br/>
            switch (datatype)<br/>
            {<br/>
                case NpoiDataType.String:<br/>
                    try<br/>
                    {<br/>
                        return row.GetCell(column).DateCellValue;<br/>
                    }<br/>
                    catch<br/>
                    {<br/>
                        try<br/>
                        {<br/>
                            return row.GetCell(column).StringCellValue;<br/>
                        }<br/>
                        catch<br/>
                        {<br/>
                            return row.GetCell(column).NumericCellValue;<br/>
                        }<br/>
                    }<br/>
                case NpoiDataType.Bool:<br/>
                    try { return row.GetCell(column).BooleanCellValue; }<br/>
                    catch { return row.GetCell(column).StringCellValue; }<br/>
                case NpoiDataType.Datetime:<br/>
                    try { return row.GetCell(column).DateCellValue; }<br/>
                    catch { return row.GetCell(column).StringCellValue; }<br/>
                case NpoiDataType.Numeric:<br/>
                    try { return row.GetCell(column).NumericCellValue; }<br/>
                    catch { return row.GetCell(column).StringCellValue; }<br/>
                case NpoiDataType.Richtext:<br/>
                    try { return row.GetCell(column).RichStringCellValue; }<br/>
                    catch { return row.GetCell(column).StringCellValue; }<br/>
                case NpoiDataType.Error:<br/>
                    try { return row.GetCell(column).ErrorCellValue; }<br/>
                    catch { return row.GetCell(column).StringCellValue; }<br/>
                case NpoiDataType.Blank:<br/>
                    try { return row.GetCell(column).StringCellValue; }<br/>
                    catch { return ""; }<br/>
                default: return "";<br/>
            }<br/>
        }

        /// <summary><br/>
        /// 获取单元格数据类型<br/>
        /// </summary><br/>
        /// <param name="hs">单元格对象</param><br/>
        /// <returns></returns><br/>
        private static NpoiDataType GetCellDataType(ICell hs)<br/>
        {<br/>
            NpoiDataType dtype;<br/>
            DateTime t1;<br/>
            var cellvalue = "";

            switch (hs.CellType)<br/>
            {<br/>
                case CellType.Blank:<br/>
                    dtype = NpoiDataType.String;<br/>
                    cellvalue = hs.StringCellValue;<br/>
                    break;<br/>
                case CellType.Boolean:<br/>
                    dtype = NpoiDataType.Bool;<br/>
                    break;<br/>
                case CellType.Numeric:<br/>
                    dtype = NpoiDataType.Numeric;<br/>
                    cellvalue = hs.NumericCellValue.ToString(CultureInfo.InvariantCulture);<br/>
                    break;<br/>
                case CellType.String:<br/>
                    dtype = NpoiDataType.String;<br/>
                    cellvalue = hs.StringCellValue;<br/>
                    break;<br/>
                case CellType.Error:<br/>
                    dtype = NpoiDataType.Error;<br/>
                    break;<br/>
                default:<br/>
                    dtype = NpoiDataType.Datetime;<br/>
                    break;<br/>
            }<br/>
            if (cellvalue != "" && DateTime.TryParse(cellvalue, out t1)) dtype = NpoiDataType.Datetime;<br/>
            return dtype;<br/>
        }

四.总结:

本文是接着上五篇介绍.NET组件,目的只是在于总结一些组件的用法,将文章作为一个引子,各位读者可以根据文章的介绍更加深入的去了解相关组件。有些地方写的有误,还望多多包涵和指正,欢迎大家给我建议介绍一些你们在项目中经常使用的组件,可以跟大家做一个分享。

.NET组件介绍系列:

一款开源免费的.NET文档操作组件DocX(.NET组件介绍之一)http://www.cnblogs.com/pengze0902/p/6122311.html

高效而稳定的企业级.NET Office 组件Spire(.NET组件介绍之二)http://www.cnblogs.com/pengze0902/p/6125570.html

最好的.NET开源免费ZIP库DotNetZip(.NET组件介绍之三)http://www.cnblogs.com/pengze0902/p/6124659.html

免费开源的DotNet二维码操作组件ThoughtWorks.QRCode(.NET组件介绍之四)http://www.cnblogs.com/pengze0902/p/6134506.html

免费开源的DotNet任务调度组件Quartz.NET(.NET组件介绍之五)http://www.cnblogs.com/pengze0902/p/6128558.html