C#MVC将数据集导出到Excel

时间:2019-01-16 20:18:21

标签: model-view-controller export-to-excel xlsx

我正在从事MVC项目。我需要将多个数据集导出到单个工作簿中的每个工作表。我正在使用ExcelLibrary跟踪示例。

how to add dataset to worksheet using Excellibrary

但是,第一个问题是它仅将数据转储到xls(Microsoft Excel 97-2003工作表)中,而不是xlsx文件中。有什么方法可以设置格式?

打开时,它首先在下面引发错误,然后打开文件

我们发现'DataFile.xls'中的某些内容存在问题。您想尽可能地恢复吗?如果您信任此工作簿的来源,请单击“是”。

第二,我不知道是否可以直接打开文件。

这是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.IO;
using ExcelLibrary.SpreadSheet;
using System.Data.SqlClient;

namespace MyProject.DAL
{
    public class ExcelExport
    {
        /// <summary>
        /// Populate all data (all converted into String) in all worksheets 
        /// from a given Excel workbook.
        /// </summary>
        /// <param name="filePath">File path of the Excel workbook</param>
        /// <returns>DataSet with all worksheet populate into DataTable</returns>
        public static DataSet CreateDataSet(String filePath)
        {
            DataSet ds = new DataSet();
            Workbook workbook = Workbook.Load(filePath);
            foreach (Worksheet ws in workbook.Worksheets)
            {
                DataTable dt = PopulateDataTable(ws);
                ds.Tables.Add(dt);
            }
            return ds;
        }
        /// <summary>
        /// Populate data (all converted into String) from a given Excel 
        /// workbook and also work sheet name into a new instance of DataTable.
        /// Returns null if given work sheet is not found.
        /// </summary>
        /// <param name="filePath">File path of the Excel workbook</param>
        /// <param name="sheetName">Worksheet name in workbook</param>
        /// <returns>DataTable with populate data</returns>
        public static DataTable CreateDataTable(String filePath, String sheetName)
        {
            Workbook workbook = Workbook.Load(filePath);
            foreach (Worksheet ws in workbook.Worksheets)
            {
                if (ws.Name.Equals(sheetName))
                    return PopulateDataTable(ws);
            }
            return null;
        }

        private static DataTable PopulateDataTable(Worksheet ws)
        {
            CellCollection Cells = ws.Cells;

            // Creates DataTable from a Worksheet
            // All values will be treated as Strings
            DataTable dt = new DataTable(ws.Name);

            // Extract columns
            for (int i = 0; i <= Cells.LastColIndex; i++)
                dt.Columns.Add(Cells[0, i].StringValue, typeof(String));

            // Extract data
            for (int currentRowIndex = 1; currentRowIndex <= Cells.LastRowIndex; currentRowIndex++)
            {
                DataRow dr = dt.NewRow();
                for (int currentColumnIndex = 0; currentColumnIndex <= Cells.LastColIndex; currentColumnIndex++)
                    dr[currentColumnIndex] = Cells[currentRowIndex, currentColumnIndex].StringValue;
                dt.Rows.Add(dr);
            }

            return dt;
        }
        private DataTable get_TblA()
        {

            using (SqlConnection con = Connection.GetConnection())
            {
                using (SqlCommand cmd = new SqlCommand(@"SELECT cola, colB
        FROM dbo.tblA;"))
                {
                    using (SqlDataAdapter da = new SqlDataAdapter())
                    {
                        DataTable dt = new DataTable();
                        cmd.CommandType = CommandType.Text;
                        cmd.Connection = con;
                        da.SelectCommand = cmd;
                        da.Fill(dt);
                        return dt;
                    }
                }
            }
        }

        private DataTable get_TblB ()
        {

            using (SqlConnection con = Connection.GetConnection())
            {
                using (SqlCommand cmd = new SqlCommand("SELECT cola, colB
        FROM dbo.tblB; "))
                {
                    using (SqlDataAdapter da = new SqlDataAdapter())
                    {
                        DataTable dt = new DataTable();
                        cmd.CommandType = CommandType.Text;
                        cmd.Connection = con;
                        da.SelectCommand = cmd;
                        da.Fill(dt);
                        return dt;
                    }
                }
            }
        }
        public DataSet getDataSetExportToExcel()
        {
            DataSet ds = new DataSet();
            DataTable dtEmp = new DataTable("TblA");
            dtEmp = get_TblA();

            DataTable dtEmpOrder = new DataTable("TblB");
            dtEmpOrder = get_TblB();
            ds.Tables.Add(dtEmp);
            ds.Tables.Add(dtEmpOrder);
            return ds;
        }
        public void SetToExport(string channel, string assets)
        {
            string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DataFile.xls");

           DataSet ds = getDataSetExportToExcel();
            CreateWorkbook(filePath, ds);

                    }
        /// <summary>
        /// Populate all data from the given DataSet into a new Excel workbook
        /// </summary>
        /// <param name="filePath">File path to new Excel workbook to be created</param>
        /// <param name="dataset">Source DataSet</param>
        public static void CreateWorkbook(String filePath, DataSet dataset)
        {
            if (dataset.Tables.Count == 0)
                throw new ArgumentException("DataSet needs to have at least one DataTable", "dataset");

            Workbook workbook = new Workbook();
            foreach (DataTable dt in dataset.Tables)
            {
                Worksheet worksheet = new Worksheet(dt.TableName);
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    // Add column header
                    worksheet.Cells[0, i] = new Cell(dt.Columns[i].ColumnName);

                    // Populate row data
                    for (int j = 0; j < dt.Rows.Count; j++)
                        worksheet.Cells[j + 1, i] = new Cell(dt.Rows[j][i]);
                }
                workbook.Worksheets.Add(worksheet);
            }

            workbook.Save(filePath);
        }

}
}

有什么建议可以解决上述两个问题吗?

0 个答案:

没有答案