datatable转换为Excel助手类

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.OleDb;
using Microsoft.Office.Interop.Excel;

namespace OA_Batch
{
    public class ExcelHelper
    {
        /// <summary>
        ///  从excel2007文件中读出dt
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public System.Data.DataTable ExcelToDataTable(string fileName)
        {
            System.Data.DataTable dt;
            string conStr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+fileName+";Extended Properties='Excel 12.0;HDR=YES;IMEX=1'";
            OleDbConnection myConn = new OleDbConnection(conStr);
            string strCom = " SELECT * FROM [Sheet1$]";
            myConn.Open();
            OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn);
            dt = new System.Data.DataTable();
            myCommand.Fill(dt);
            myConn.Close();
            return dt;
        }


        public void DataTabletoExcel(System.Data.DataTable tmpDataTable, string strFileName)
        {

            if (tmpDataTable == null)

                return;

            int rowNum = tmpDataTable.Rows.Count;

            int columnNum = tmpDataTable.Columns.Count;

            int rowIndex = 1;

            int columnIndex = 0;

            Application xlApp = new ApplicationClass();

            xlApp.DefaultFilePath = "";

            xlApp.DisplayAlerts = true;

            xlApp.SheetsInNewWorkbook = 1;

            Workbook xlBook = xlApp.Workbooks.Add(true);

            //将DataTable的列名导入Excel表第一行

            foreach (DataColumn dc in tmpDataTable.Columns)
            {

                columnIndex++;

                xlApp.Cells[rowIndex, columnIndex] = dc.ColumnName;

            }

            //将DataTable中的数据导入Excel中

            for (int i = 0; i < rowNum; i++)
            {

                rowIndex++;

                columnIndex = 0;

                for (int j = 0; j < columnNum; j++)
                {

                    columnIndex++;

                    xlApp.Cells[rowIndex, columnIndex] = tmpDataTable.Rows[i][j].ToString();

                }

            }

            //xlBook.SaveCopyAs(HttpUtility.UrlDecode(strFileName, System.Text.Encoding.UTF8));

            xlBook.SaveCopyAs(strFileName);
            xlBook.Close(false);

        }

    }


}

原文地址:https://www.cnblogs.com/a1991322/p/2650682.html