---
title: "Excel 数据导入导出"
author: "cab0605"
date: "2011-04-12T21:49:33Z"
tags: ["C", "C#", "C++", "Excel"]
categories: ["Web前端"]
slug: "excel"
draft: false
lastmod: "2011-04-12T21:49:33Z"
id: 1000393
url: "https://cab0605.iteye.com/blog/1000393"
---

//导出控件Aspose.Cells 必须引用该控件

using System;  
using System.Data;  
using System.Data.OleDb;  
using System.Collections;  
using System.Configuration;  
using System.Collections.Generic;

using System.IO;  
using Aspose.Cells;

namespace BLL  
{  
    public class ImportExportExcel  
    {  
        private static string outFileName = "";  
        private static Workbook workbook = null;  
        private static Worksheet worksheet = null;

        private static void AddTitle(string title, int columnCount)  
        {   //创建标题  
            //合并单元格  
            worksheet.Cells.Merge(0, 0, 1, columnCount);  
            worksheet.Cells.Merge(1, 0, 1, columnCount);  
            Cell cell\_title = worksheet.Cells\[0, 0];  
            Cell cell\_date  = worksheet.Cells\[1, 0];

            cell\_title.PutValue(title, true);  
            cell\_title.Style.HorizontalAlignment = TextAlignmentType.Center;  
            cell\_title.Style.Font.Name = "黑体";  
            cell\_title.Style.Font.Size = 18;  
            cell\_title.Style.Font.IsBold = true;  
            cell\_date.PutValue("查询时间：" + DateTime.Now.ToLocalTime(), true);  
            cell\_date.SetStyle(cell\_title.Style);  
        }

        private static void AddHeader(DataTable dt)  
        {   //生成列名标题  
            Cell cell = null;  
            for (int col = 0; col &lt; dt.Columns.Count; col++)  
            {  
                cell = worksheet.Cells\[2, col];  
                cell.PutValue(dt.Columns\[col].ColumnName);  
                cell.Style.Font.IsBold = true;  
            }  
        }

        private static void AddBody(DataTable dt)  
        {   //生成指定数据到EXCEL中；  
            long ll\_count;  
            ll\_count = dt.Rows.Count;  
            for (int r = 0; r &lt; ll\_count; r++)  
            {  
                for (int c = 0; c &lt; dt.Columns.Count; c++)  
                {  
                    worksheet.Cells\[r + 3, c].PutValue(dt.Rows\[r]\[c].ToString());  
                }  
            }  
        }

        public static string DatatableToExcel(DataTable dt, string fileTitle, string sheetName,string fileName)  
        {

            try  
            {  
                workbook = new Workbook();  
                workbook.Worksheets.Clear();  
                string ls\_path\_dir;  
                ls\_path\_dir = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;  
                string ls\_filename;  
                string ls\_filepath;  
                //按时间生成指定文件名  
                ls\_filename = fileName + System.DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";  
                //生成文件在服务器的地址  
                ls\_filepath = ls\_path\_dir + "Exportfile\\\\" + ls\_filename;  
                //判断文件是否存在，存在则删除文件；

                if (File.Exists(ls\_filepath))  
                { File.Delete(ls\_filepath); }

                if(sheetName.Length == 0)  
                { sheetName = "Sheet"; }

                workbook.Worksheets.Add(sheetName);  
                worksheet = workbook.Worksheets\[0];

                //worksheet.Name = sheetName;  
                outFileName = ls\_filepath;

                AddTitle(fileTitle, dt.Columns.Count);  
                AddHeader(dt);  
                AddBody(dt);  
                //保存生成文件  
                worksheet.AutoFitColumns();  
                worksheet.AutoFitRows();  
                workbook.Save(outFileName);  
                return ls\_filepath;  
            }  
            catch (SystemException)

            { return "";  
            }  
        }

        public static DataTable ExcelToDatatable(string excelFileName)  
        {  
            Workbook book = new Workbook();  
            book.Open(excelFileName);  
            Worksheet sheet = book.Worksheets\[0];  
            Cells cells = sheet.Cells;  
            //获取excel中的数据保存到一个datatable中  
            DataTable dt\_Import = cells.ExportDataTableAsString(0, 0, cells.MaxDataRow + 1, cells.MaxDataColumn + 1, false);  
            //dt\_Import.  
            return dt\_Import;  
        }  
    }  
}