Cách xuất DataTable sang Excel


107

Làm cách nào để xuất a DataTablesang Excel trong C #? Tôi đang sử dụng Windows Forms. Các DataTableđược liên kết với một DataGridViewkiểm soát. Tôi phải xuất bản ghi DataTablesang Excel.


Cách dễ nhất là thực hiện một vòng lặp foreach lồng nhau trên các mục và subitem.
Saeid Yazdani

LƯU Ý: Nếu bạn đang cố gắng chuyển các giá trị từ bảng dữ liệu sang một đối tượng sau đó sang Excel, bạn cũng nên xử lý lỗi kiểu dữ liệu. Ví dụ: Guids sẽ kết thúc nhiệm vụ của bạn với ngoại lệ HRESULT: 0x800A03EC. Một cách khắc phục mà không cần kiểm tra kiểu dữ liệu là sử dụng "ToString ()" khi điền đối tượng của bạn. Excel sẽ tự chuyển đổi các số về định dạng số. FlashTrev như đã giải quyết vấn đề liên quan về ngày / giờ.
u8it

Tôi muốn giới thiệu câu trả lời cho câu hỏi này: stackoverflow.com/a/536699/1367391
Troy Cosentino

Câu trả lời:


129

Tôi muốn giới thiệu ClosedXML -

Bạn có thể biến DataTable thành một trang tính Excel với một số mã rất dễ đọc:

XLWorkbook wb = new XLWorkbook();
DataTable dt = GetDataTableOrWhatever();
wb.Worksheets.Add(dt,"WorksheetName");

Nhà phát triển phản hồi nhanh và hữu ích. Dự án được phát triển tích cực và tài liệu là tuyệt vời.


7
Thêm ~ 6 MB thư viện tham chiếu sẽ không làm cho ứng dụng nặng hơn?
ʞᴉɯ

4
Câu hỏi hay @MicheleVirgilio. Tôi chưa thực hiện bất kỳ thử nghiệm nào để định lượng tác động. Nhưng đối với những gì nó đáng giá, nó đã không làm phiền tôi trong bất kỳ dự án nào tôi đã sử dụng nó, thực tế tôi không thể nói rằng tôi đã từng nhận thấy nó.
hmqcnoesy

Mã này trở cho tôi một excel với một cột duy nhất có giá trịClosedXML.Excel.XLWorkbook
Đó là một cái bẫy

78

Hãy thử mã đơn giản, để chuyển đổi DataTable sang tệp excel dưới dạng csv:

var lines = new List<string>();

string[] columnNames = dataTable.Columns
    .Cast<DataColumn>()
    .Select(column => column.ColumnName)
    .ToArray();

var header = string.Join(",", columnNames.Select(name => $"\"{name}\""));
lines.Add(header);

var valueLines = dataTable.AsEnumerable()
    .Select(row => string.Join(",", row.ItemArray.Select(val => $"\"{val}\"")));

lines.AddRange(valueLines);

File.WriteAllLines("excel.csv", lines);

Thao tác này sẽ ghi một tệp mới excel.csvvào thư mục làm việc hiện tại , thường là nơi chứa .exe hoặc nơi bạn khởi chạy nó từ đó.


1
Thật là một câu trả lời xuất sắc, anh bạn. Tôi không có phạm vi để đưa ra nhiều hơn một phiếu ủng hộ cho câu trả lời của bạn, nếu không, tôi đã có thể đưa ra hơn 100 phiếu ủng hộ.
Ashok kumar

2
@Cuong Le - Nếu ô có hai dấu phẩy thì đó là sự cố tại "string.Join (", ")"
suneel ranga 11/05

@Cuong Le "excel.csv"địa điểm sẽ ở đâu?
Jogi

2
@suneelranga - Nếu một ô (tức là trong row.ItemArray) chứa ,(dấu phẩy) thì theo tiêu chuẩn CSV, ô đó sẽ được tăng thêm bởi dấu ngoặc kép ","và sau đó xuất hiện trong tệp như bình thường. Vì vậy, có - nó sẽ gây ra sự cố vì mã này không phát hiện ,và áp dụng dấu ngoặc kép.
Tom Leys

1
@ Si8 sau khi được lưu, bạn có thể thực hiện Process.Start (Your File) và nó sẽ mở ra cho họ. Tôi tin là gần như bạn có thể hiểu được ..
TimmRH

40

Một tùy chọn thanh lịch là viết một phương thức mở rộng (xem bên dưới) cho lớp DataTable của khung .net.

Phương pháp mở rộng này có thể được gọi như sau:

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

DataTable dt;
// fill table data in dt here 
...

// export DataTable to excel
// save excel file without ever making it visible if filepath is given
// don't save excel file, just make it visible if no filepath is given
dt.ExportToExcel(ExcelFilePath);

Phương thức mở rộng cho lớp DataTable:

public static class My_DataTable_Extensions
{

    // Export DataTable into an excel file with field names in the header line
    // - Save excel file without ever making it visible if filepath is given
    // - Don't save excel file, just make it visible if no filepath is given
    public static void ExportToExcel(this DataTable tbl, string excelFilePath = null) {
        try {
            if (tbl == null || tbl.Columns.Count == 0)
                throw new Exception("ExportToExcel: Null or empty input table!\n");

            // load excel, and create a new workbook
            var excelApp = new Excel.Application();
            excelApp.Workbooks.Add();

            // single worksheet
            Excel._Worksheet workSheet = excelApp.ActiveSheet;

            // column headings
            for (var i = 0; i < tbl.Columns.Count; i++) {
                workSheet.Cells[1, i + 1] = tbl.Columns[i].ColumnName;
            }

            // rows
            for (var i = 0; i < tbl.Rows.Count; i++) {
                // to do: format datetime values before printing
                for (var j = 0; j < tbl.Columns.Count; j++) {
                    workSheet.Cells[i + 2, j + 1] = tbl.Rows[i][j];
                }
            }

            // check file path
            if (!string.IsNullOrEmpty(excelFilePath)) {
                try {
                    workSheet.SaveAs(excelFilePath);
                    excelApp.Quit();
                    MessageBox.Show("Excel file saved!");
                }
                catch (Exception ex) {
                    throw new Exception("ExportToExcel: Excel file could not be saved! Check filepath.\n"
                                        + ex.Message);
                }
            } else { // no file path is given
                excelApp.Visible = true;
            }
        }
        catch (Exception ex) {
            throw new Exception("ExportToExcel: \n" + ex.Message);
        }
    }
}

20
Lưu ý rằng điều này cần phải cài đặt Excel.
Banshee

5
ExcelFilePath != null && ExcelFilePath != ""có thể là!String.IsNullOrEmpty(ExcelFilePath)
Mark Schultheiss

2
Một lưu ý: Microsoft không khuyến cáo sử dụng Interop trên máy chủ support.microsoft.com/en-us/help/257757/...
alex.pulver

@ alex.pulver nó cũng không hoạt động khi tôi cố gắng sử dụng nó trên máy chủ. Điểm tốt cần đề cập.
Si8

Điều này sẽ hiệu quả nhưng nó chậm. Tốt nhất bạn nên sao chép vào khay nhớ tạm và dán vào excel. Nếu bạn làm việc trên hơn 1000 bản ghi, điều này sẽ mất một lúc.
Alex M

25

Giải pháp dựa trên bài báo tuncalik (cảm ơn vì ý tưởng), nhưng trong trường hợp bảng lớn hoạt động nhanh hơn nhiều (và kém rõ ràng hơn một chút).

public static class My_DataTable_Extensions
{
    /// <summary>
    /// Export DataTable to Excel file
    /// </summary>
    /// <param name="DataTable">Source DataTable</param>
    /// <param name="ExcelFilePath">Path to result file name</param>
    public static void ExportToExcel(this System.Data.DataTable DataTable, string ExcelFilePath = null)
    {
        try
        {
            int ColumnsCount;

            if (DataTable == null || (ColumnsCount = DataTable.Columns.Count) == 0)
                throw new Exception("ExportToExcel: Null or empty input table!\n");

            // load excel, and create a new workbook
            Microsoft.Office.Interop.Excel.Application Excel = new Microsoft.Office.Interop.Excel.Application();
            Excel.Workbooks.Add();

            // single worksheet
            Microsoft.Office.Interop.Excel._Worksheet Worksheet = Excel.ActiveSheet;

            object[] Header = new object[ColumnsCount];

            // column headings               
            for (int i = 0; i < ColumnsCount; i++)
                Header[i] = DataTable.Columns[i].ColumnName;

            Microsoft.Office.Interop.Excel.Range HeaderRange = Worksheet.get_Range((Microsoft.Office.Interop.Excel.Range)(Worksheet.Cells[1, 1]), (Microsoft.Office.Interop.Excel.Range)(Worksheet.Cells[1, ColumnsCount]));
            HeaderRange.Value = Header;
            HeaderRange.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightGray);
            HeaderRange.Font.Bold = true;

            // DataCells
            int RowsCount = DataTable.Rows.Count;
            object[,] Cells = new object[RowsCount, ColumnsCount];

            for (int j = 0; j < RowsCount; j++)
                for (int i = 0; i < ColumnsCount; i++)
                    Cells[j, i] = DataTable.Rows[j][i];

            Worksheet.get_Range((Microsoft.Office.Interop.Excel.Range)(Worksheet.Cells[2, 1]), (Microsoft.Office.Interop.Excel.Range)(Worksheet.Cells[RowsCount + 1, ColumnsCount])).Value = Cells;

            // check fielpath
            if (ExcelFilePath != null && ExcelFilePath != "")
            {
                try
                {
                    Worksheet.SaveAs(ExcelFilePath);
                    Excel.Quit();
                    System.Windows.MessageBox.Show("Excel file saved!");
                }
                catch (Exception ex)
                {
                    throw new Exception("ExportToExcel: Excel file could not be saved! Check filepath.\n"
                        + ex.Message);
                }
            }
            else    // no filepath is given
            {
                Excel.Visible = true;
            }
        }
        catch (Exception ex)
        {
            throw new Exception("ExportToExcel: \n" + ex.Message);
        }
    }
}

Câu trả lời của tuncalik mất gần một phút đối với tôi, đây là 1 giây nếu nó mất nhiều thời gian ... Tôi thực sự giật mình.
Wilsu

2
Đây là mẫu nhanh nhất mà tôi đã thử, rất tốt. Tôi đã phải sử dụng Marshal để giải phóng tệp sau đó. Excel.Quit(); Marshal.FinalReleaseComObject(Worksheet); Marshal.FinalReleaseComObject(HeaderRange); Marshal.FinalReleaseComObject(Excel);
Dave Kelly

Nó có làm hỏng Office để được cài đặt không?
Parshuram Kalvikatte

Hoạt động hoàn toàn khác, nhưng màu nền của Header Back luôn được đặt thành Đen khi sử dụng giải pháp này trong ứng dụng bảng điều khiển. Điều gì có thể là lý do??
Zaveed Abbasi

15

Hãy thử chức năng này truyền dữ liệu và đường dẫn tệp mà bạn muốn xuất

public void CreateCSVFile(ref DataTable dt, string strFilePath)
{            
    try
    {
        // Create the CSV file to which grid data will be exported.
        StreamWriter sw = new StreamWriter(strFilePath, false);
        // First we will write the headers.
        //DataTable dt = m_dsProducts.Tables[0];
        int iColCount = dt.Columns.Count;
        for (int i = 0; i < iColCount; i++)
        {
            sw.Write(dt.Columns[i]);
            if (i < iColCount - 1)
            {
                sw.Write(",");
            }
        }
        sw.Write(sw.NewLine);

        // Now write all the rows.

        foreach (DataRow dr in dt.Rows)
        {
            for (int i = 0; i < iColCount; i++)
            {
                if (!Convert.IsDBNull(dr[i]))
                {
                    sw.Write(dr[i].ToString());
                }
                if (i < iColCount - 1)
                {
                    sw.Write(",");
                }
            }

            sw.Write(sw.NewLine);
        }
        sw.Close();
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

1
Lưu ý rằng điều này sẽ không thực sự sử dụng các ô bảng trong tài liệu Excel, thay vào đó mọi thứ cho mỗi hàng sẽ được in trên ô đầu tiên của mỗi hàng.
Banshee

@Banshee Không, Excel hoàn toàn hiểu các tệp CSV.
NickG

Cũng không hoạt động với excel của tôi. Dữ liệu của mỗi hàng nằm trong ô đầu tiên.
Mitulát Bati

5

Cách tốt nhất và dễ nhất

private void exportToExcel(DataTable dt)
    {

        /*Set up work book, work sheets, and excel application*/
        Microsoft.Office.Interop.Excel.Application oexcel = new Microsoft.Office.Interop.Excel.Application();
        try
        {
            string path = AppDomain.CurrentDomain.BaseDirectory;
            object misValue = System.Reflection.Missing.Value;
            Microsoft.Office.Interop.Excel.Workbook obook = oexcel.Workbooks.Add(misValue);
            Microsoft.Office.Interop.Excel.Worksheet osheet = new Microsoft.Office.Interop.Excel.Worksheet();


          //  obook.Worksheets.Add(misValue);

            osheet = (Microsoft.Office.Interop.Excel.Worksheet)obook.Sheets["Sheet1"];
            int colIndex = 0;
            int rowIndex = 1;

            foreach (DataColumn dc in dt.Columns)
            {
                colIndex++;
                osheet.Cells[1, colIndex] = dc.ColumnName;
            }
            foreach (DataRow dr in dt.Rows)
            {
                rowIndex++;
                colIndex = 0;

                foreach (DataColumn dc in dt.Columns)
                {
                    colIndex++;
                    osheet.Cells[rowIndex, colIndex] = dr[dc.ColumnName];
                }
            }

            osheet.Columns.AutoFit();
            string filepath = "C:\\Temp\\Book1";

            //Release and terminate excel

            obook.SaveAs(filepath);
            obook.Close();
            oexcel.Quit();
            releaseObject(osheet);

            releaseObject(obook);

            releaseObject(oexcel);
            GC.Collect();
        }
        catch (Exception ex)
        {
            oexcel.Quit();
            log.AddToErrorLog(ex, this.Name);
        }
    }

1
private void releaseObject(object o) { try { while (System.Runtime.InteropServices.Marshal.ReleaseComObject(o) > 0) { } } catch { } finally { o = null; } }
Tim

(vui lòng ở đây) nếu có nhiều hơn một tệp excel đang mở, hàm phát hành này có hủy tất cả chúng hay chỉ một tệp được truyền dưới dạng tham số?
Elliott Addi

1

Excel Interop:

Phương pháp này ngăn Ngày bị chuyển từ dd-mm-yyyy sang mm-dd-yyyy

public bool DataTableToExcelFile(DataTable dt, string targetFile)
{
    const bool dontSave = false;
    bool success = true;

    //Exit if there is no rows to export
    if (dt.Rows.Count == 0) return false;

    object misValue = System.Reflection.Missing.Value;
    List<int> dateColIndex = new List<int>();
    Excel.Application excelApp = new Excel.Application();
    Excel.Workbook excelWorkBook = excelApp.Workbooks.Add(misValue);
    Excel.Worksheet excelWorkSheet = excelWorkBook.Sheets("sheet1");

    //Iterate through the DataTable and populate the Excel work sheet
    try {
        for (int i = -1; i <= dt.Rows.Count - 1; i++) {
            for (int j = 0; j <= dt.Columns.Count - 1; j++) {
                if (i < 0) {
                    //Take special care with Date columns
                    if (dt.Columns(j).DataType is typeof(DateTime)) {
                        excelWorkSheet.Cells(1, j + 1).EntireColumn.NumberFormat = "d-MMM-yyyy;@";
                        dateColIndex.Add(j);
                    } 
                    //else if ... Feel free to add more Formats

                    else {
                        //Otherwise Format the column as text
                        excelWorkSheet.Cells(1, j + 1).EntireColumn.NumberFormat = "@";
                    }
                    excelWorkSheet.Cells(1, j + 1) = dt.Columns(j).Caption;
                } 
                else if (dateColIndex.IndexOf(j) > -1) {
                    excelWorkSheet.Cells(i + 2, j + 1) = Convert.ToDateTime(dt.Rows(i).ItemArray(j)).ToString("d-MMM-yyyy");
                } 
                else {
                    excelWorkSheet.Cells(i + 2, j + 1) = dt.Rows(i).ItemArray(j).ToString();
                }
            }
        }

        //Add Autofilters to the Excel work sheet  
        excelWorkSheet.Cells.AutoFilter(1, Type.Missing, Excel.XlAutoFilterOperator.xlAnd, Type.Missing, true);
        //Autofit columns for neatness
        excelWorkSheet.Columns.AutoFit();
        if (File.Exists(exportFile)) File.Delete(exportFile);
        excelWorkSheet.SaveAs(exportFile);
    } catch {
        success = false;
    } finally {
        //Do this irrespective of whether there was an exception or not. 
        excelWorkBook.Close(dontSave);
        excelApp.Quit();
        releaseObject(excelWorkSheet);
        releaseObject(excelWorkBook);
        releaseObject(excelApp);
    }
    return success;
}

Nếu bạn không quan tâm đến Ngày được lật, hãy sử dụng liên kết xem cho biết cách điền tất cả các ô trong bảng tính Excel trong một dòng mã:

Excel Interop - Hiệu quả và hiệu suất

CSV:

public string DataTableToCSV(DataTable dt, bool includeHeader, string rowFilter, string sortFilter, bool useCommaDelimiter = false, bool truncateTimesFromDates = false)
{
    dt.DefaultView.RowFilter = rowFilter;
    dt.DefaultView.Sort = sortFilter;
    DataView dv = dt.DefaultView;
    string csv = DataTableToCSV(dv.ToTable, includeHeader, useCommaDelimiter, truncateTimesFromDates);
    //reset the Filtering
    dt.DefaultView.RowFilter = string.Empty;
    return csv;
}

public string DataTableToCsv(DataTable dt, bool includeHeader, bool useCommaDelimiter = false, bool truncateTimesFromDates = false)
{
    StringBuilder sb = new StringBuilder();
    string delimter = Constants.vbTab;
    if (useCommaDelimiter)
        delimter = ",";

    if (includeHeader) {
        foreach (DataColumn dc in dt.Columns) {
            sb.AppendFormat("{0}" + Constants.vbTab, dc.ColumnName);
        }

        //remove the last Tab
        sb.Remove(sb.ToString.Length - 1, 1);
        sb.Append(Environment.NewLine);
    }

    foreach (DataRow dr in dt.Rows) {
        foreach (DataColumn dc in dt.Columns) {
            if (Information.IsDate(dr(dc.ColumnName).ToString()) & dr(dc.ColumnName).ToString().Contains(".") == false & truncateTimesFromDates) {
                sb.AppendFormat("{0}" + delimter, Convert.ToDateTime(dr(dc.ColumnName).ToString()).Date.ToShortDateString());
            } else {
                sb.AppendFormat("{0}" + delimter, CheckDBNull(dr(dc.ColumnName).ToString().Replace(",", "")));
            }
        }
        //remove the last Tab
        sb.Remove(sb.ToString.Length - 1, 1);
        sb.Append(Environment.NewLine);
    }
    return sb.ToString;
}

public enum enumObjectType
{
    StrType = 0,
    IntType = 1,
    DblType = 2
}

public object CheckDBNull(object obj, enumObjectType ObjectType = enumObjectType.StrType)
{
    object objReturn = null;
    objReturn = obj;
    if (ObjectType == enumObjectType.StrType & Information.IsDBNull(obj)) {
        objReturn = "";
    } else if (ObjectType == enumObjectType.IntType & Information.IsDBNull(obj)) {
        objReturn = 0;
    } else if (ObjectType == enumObjectType.DblType & Information.IsDBNull(obj)) {
        objReturn = 0.0;
    }
    return objReturn;
}

1

Chỉ cần sử dụng Thư viện CloseMXL.Excel . Nó cũng dễ dàng và khá nhanh chóng.

Lớp học

private DataTable getAllList()
        {
            string constr = ConfigurationManager.ConnectionStrings["RConnection"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("SELECT EmpId, gender, EmpName, pOnHold FROM Employee  WHERE EmpId= '"+ AnyVariable + "' ORDER BY EmpName"))
                {
                    using (SqlDataAdapter da = new SqlDataAdapter())
                    {
                        DataTable dt = new DataTable();
                        cmd.CommandType = CommandType.Text;
                        cmd.Connection = con;
                        da.SelectCommand = cmd;
                        da.Fill(dt);
                        dt.Columns[0].ColumnName = "Employee Id";
                        dt.Columns[1].ColumnName = "Gender";
                        dt.Columns[2].ColumnName = "Employee Name";
                        dt.Columns[3].ColumnName = "On Hold";

                        return dt;
                    }
                }
            }
        }

Sau đó, một phương thức khác lấy Dataset

public DataSet getDataSetExportToExcel()
        {
            DataSet ds = new DataSet();
            DataTable dtEmp = new DataTable("CLOT List");
            dtEmp = getAllList();
             ds.Tables.Add(dtEmp);
             ds.Tables[0].TableName = "Employee"; //If you which to use Mutliple Tabs
             return ds;
          }

Bây giờ bạn bấm nút Sự kiện

protected void btn_Export_Click(object sender, EventArgs e)
        {
            DataSet ds = getDataSetExportToExcel();

            using (XLWorkbook wb = new XLWorkbook())
            {
                wb.Worksheets.Add(ds);
                wb.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                wb.Style.Font.Bold = true;

                Response.Clear();
                Response.Buffer = true;
                Response.Charset = "";
                Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                Response.AddHeader("content-disposition", "attachment;filename=EmployeeonHoldList.xlsx");

                using (MemoryStream MyMemoryStream = new MemoryStream())
                {
                    wb.SaveAs(MyMemoryStream);
                    MyMemoryStream.WriteTo(Response.OutputStream);

                    Response.Flush();
                    Response.End();
                }
            }
        }

1

Bạn có thể sử dụng thư viện SwiftExcel của tôi . Nó đặc biệt tốt khi hiệu suất và mức sử dụng bộ nhớ thấp được đưa ra vì nó ghi dữ liệu trực tiếp vào tệp:

using (var ew = new ExcelWriter("C:\\temp\\test.xlsx"))
{
    for (var row = 1; row <= 100; row++)
    {
        for (var col = 1; col <= 10; col++)
        {
            ew.Write($"row:{row}-col:{col}", col, row);
        }
    }
}

Lệnh Nuget để cài đặt:

Install-Package SwiftExcel

1

Tôi muốn thêm câu trả lời này vì tôi đã dành rất nhiều thời gian để tìm kiếm một phương pháp nhanh chóng, đáng tin cậy để thực hiện việc này và không có ví dụ hoàn chỉnh nào về việc sử dụng OpenXMLWriter cho mục đích này tồn tại ở bất cứ đâu mà tôi có thể tìm thấy.

Đầu tiên, COM / Interop (mà nhiều câu trả lời khác sử dụng) là OK cho mục đích này, nhưng nó có một số nhạy cảm. Tôi đã sử dụng nó trong nhiều thập kỷ và nó hầu như ổn định, nhưng khi triển khai front-end kho dữ liệu cho hàng trăm người dùng, tôi thấy nó có quá nhiều vấn đề tùy thuộc vào máy và những gì người dùng đã làm, vì vậy tôi đã chuyển sang OpenXML. OpenXML DOM khá tốt cho mục đích này, nhưng nó chậm hơn so với sử dụng OpenXMLWriter. Khi bạn truy cập vào bộ dữ liệu lớn (100K +) với nhiều cột, DOM chậm hơn nhiều so với OpenXMLWriter, vì vậy tôi sử dụng cái sau. Phương pháp dưới đây viết 420K + hàng với hơn 30 trường trong vòng chưa đầy 30 giây.

Tôi hy vọng các nhận xét là đủ để hướng dẫn mọi người thông qua những gì nó đang làm. Nó được đơn giản hóa, ở chỗ nó ghi tất cả các giá trị vào tệp dưới dạng chuỗi, nhưng bạn có thể triển khai logic để ghi các kiểu dữ liệu khác nhau (và sử dụng các định dạng ô khác nhau) dựa trên nội dung dữ liệu của bạn. Bạn cũng có thể điều chỉnh điều này để sử dụng trên DataGridView (thay vì DataTable) bằng cách chỉ thay đổi một số thứ (cụ thể là các vòng qua các cột / hàng).

Tham chiếu đến DocumentFormat.OpenXML (d / l với OpenXML SDK) và WindowsBase là bắt buộc.

Imports DocumentFormat.OpenXml
Imports DocumentFormat.OpenXml.Spreadsheet
Imports DocumentFormat.OpenXml.Packaging

Public Sub ExportToExcelXML(ByRef dt As DataTable, filename As String)
    Dim wbp As WorkbookPart, wsp As WorksheetPart
    'If this DataTable has more rows in it than can fit in Excel, throw an exception
    If dt.Rows.Count > 1048575 Then Throw New Exception("The DataTable is too large to export to Excel.")
    'Delete any previous file of the same name that may exist.
    File.Delete(filename)
    'Create an OpenXML SpreadsheetDocument...
    Using xls = SpreadsheetDocument.Create(filename, SpreadsheetDocumentType.Workbook)
        'Add a WorkbookPart to the Spreadsheet Doc, then add a WorksheetPart to the WorkbookPart.
        wbp = xls.AddWorkbookPart()
        wsp = wbp.AddNewPart(Of WorksheetPart)
        'Now we need to add the "StyleSheet" to the WorkbookPart (that we just added above). This will allow us to apply formatting to our Cells.
        'Add the WbStylesPart and the StyleSheet.
        Dim stp As WorkbookStylesPart = wbp.AddNewPart(Of WorkbookStylesPart)
        Dim ss As New Stylesheet
        'Create the only two Fonts we're going to use (Regular and Bold).
        Dim fBold As New Font
        fBold.Append(New Bold)
        Dim fnts As New Fonts
        fnts.Append(New Font) 'This creates the default (unmodified, regular) Font. It's added first, so its index is 0.
        fnts.Append(fBold) 'This creates the Bold font. It's added second, so its index is 1.
        'Create the default Fill/Border settings (these have to be here, even though I don't set any custom fills/borders).
        Dim flls As New Fills
        Dim brdrs As New Borders
        flls.Append(New Fill)
        brdrs.Append(New Border)
        'Now I have to add formats (NumberFormat and CellFormat). First, you create a NumberFormat. This is basically the pattern of 
        '   the format (i.e. "@" for Text). For now, I only need a Text format, but I can add more patterns if needed.
        '   I give the format an ID of 164, since 163 is where the built-in Excel formats end.
        Dim nbrfmts As New NumberingFormats
        nbrfmts.Append(New NumberingFormat With {.NumberFormatId = 164, .FormatCode = "@"})
        'Create the first two CellFormats: Default, which will have an index of 0 and "Header" (Bold/Centered) with an index of 1.
        Dim cellfmts As New CellFormats()
        cellfmts.Append(New CellFormat() With {.FontId = 0, .NumberFormatId = 164, .FillId = 0, .BorderId = 0})
        cellfmts.Append(New CellFormat() With {.FontId = 1, .NumberFormatId = 164,
            .Alignment = New Alignment() With {.WrapText = True, .Horizontal = HorizontalAlignmentValues.Center}})
        'Add all of the Fonts/Fills/Borders/etc to the StyleSheet and add it all to the WorkbookStylesPart.
        ss.Append(fnts)
        ss.Append(flls)
        ss.Append(brdrs)
        ss.Append(cellfmts)
        ss.NumberingFormats = nbrfmts
        stp.Stylesheet = ss
        stp.Stylesheet.Save()
        'Now create an OpenXMLWriter using the WorksheetPart to write the cells to the worksheet.
        Using oxw As OpenXmlWriter = OpenXmlWriter.Create(wsp)
            'Write the start element for the Worksheet and the Columns...
            oxw.WriteStartElement(New Worksheet)
            oxw.WriteStartElement(New Columns())
            'Now I'm going to loop through the columns in the DataTable...
            For c As Integer = 0 To dt.Columns.Count - 1
                'Now we'll get the width for the column. To do this, we loop through all of the rows and measure the width of the text 
                '   using the default Excel Font (currently Font: Calibri Size: 11) and return the largest width (in pixels) to use below.
                '   Why not do this loop below (when I loop through the rows to write the Cells)? Because you can't. You have to
                '   write the Column XML first before writing the SheetData/Row/Cell XML (I confirmed this by trying it), so there's
                '   no way (that I'm aware of) to avoid looping through all of the rows twice if you want to AutoFit.
                'Setup vars we'll use for getting the column widths (below).
                Dim g = System.Drawing.Graphics.FromHwnd(IntPtr.Zero)
                Dim fnt = New System.Drawing.Font("Calibri", 11)
                Dim wid As Double = 0
                'Get the width of the header (because if this is wider than the widest value, we'll use the header text's width).
                '   I found that adding 2 pixels to the width was necessary to get the column as wide as Excel would make it.
                Dim tmp As Double = g.MeasureString(dt.Columns(c).ColumnName, New System.Drawing.Font(fnt, System.Drawing.FontStyle.Bold)).Width + 2
                'Loop through the rows in the dt and get the width of the value in that row/col. If it's wider than the widest
                '   width we've encountered thus far, use the new wider width as our basis.
                For Each row As DataRow In dt.Rows
                    If tmp > wid Then wid = tmp
                    tmp = g.MeasureString(row(c).ToString, fnt).Width
                Next
                'Set the column attributes and write it to the file. The Width is set using a formula that converts from pixels to Excel's column width values.
                Dim oxa As New List(Of OpenXmlAttribute) From {New OpenXmlAttribute("min", Nothing, c + 1), New OpenXmlAttribute("max", Nothing, c + 1),
                    New OpenXmlAttribute("width", Nothing, System.Math.Round((wid - 12 + 5) / 7D + 1, 2))}
                oxw.WriteStartElement(New Column(), oxa)
                oxw.WriteEndElement()
            Next
            'CLose out the Columns collection.
            oxw.WriteEndElement()
            'Write the start element for the SheetData...
            oxw.WriteStartElement(New SheetData)
            'Write the start element for the Header row.
            oxw.WriteStartElement(New Row)
            'Loop through the Columns in the dt.
            For Each col As DataColumn In dt.Columns
                'Write a cell for this column's Header. All Header cells are written with a DataType of String ("str"). 
                '   I ALSO apply the "Header" CellFormat (StyleIndex 1) to all of the Header Cells. This makes them Bold and Centered.
                WriteCell(oxw, col.ColumnName, "str", 1)
            Next
            'Close out the Header row.
            oxw.WriteEndElement()
            'Loop through all of the rows in the dt...
            For Each row As DataRow In dt.Rows
                'Write a StartElement for this row...
                oxw.WriteStartElement(New Row)
                'Loop through all of the columns in the dt...
                For c As Integer = 0 To dt.Columns.Count - 1
                    'Write a value in this row/column to the Excel file. I use the datatype of "String" and the default CellFormat/StyleIndex.
                    WriteCell(oxw, row(c).ToString, "str", 0)
                Next
                'Close out this row.
                oxw.WriteEndElement()
            Next
            'Close out the Worksheet and SheetData elements...
            oxw.WriteEndElement()
            oxw.WriteEndElement()
        End Using
        'Now we're going to create an OpenXMLWriter using the WorkbookPart (that we created above)...
        Using oxw As OpenXmlWriter = OpenXmlWriter.Create(wbp)
            'Add starting elements for the Workbook and Sheets collection.
            oxw.WriteStartElement(New Workbook())
            oxw.WriteStartElement(New Sheets())
            'Add the Sheet (name the Sheet after the file name minus the extension).
            oxw.WriteElement(New Sheet() With {.Name = Path.GetFileNameWithoutExtension(filename), .SheetId = 1, .Id = xls.WorkbookPart.GetIdOfPart(wsp)})
            'Write End elements for the Workbook/Sheets
            oxw.WriteEndElement()
            oxw.WriteEndElement()
        End Using
    End Using

End Sub

'This Sub is used to write a value to a Cell using OpenXMLWriter.
Private Sub WriteCell(ByRef oxw As OpenXmlWriter, value As String, datatype As String, style As UInt32Value)
    Dim oxa As New List(Of OpenXmlAttribute) From {New OpenXmlAttribute("t", Nothing, datatype), New OpenXmlAttribute("s", Nothing, style)}
    oxw.WriteStartElement(New Cell(), oxa)
    If value <> Nothing Then oxw.WriteElement(New CellValue(value))
    oxw.WriteEndElement()
End Sub

1
Cảm ơn rất nhiều vì đã dành thời gian cho câu trả lời này. Tôi có một khách hàng có giải pháp hoạt động trong Excel Interop, nhưng đang phàn nàn về việc nó chạy chậm như thế nào. Tôi đã thấy một số câu trả lời khác cho các câu hỏi hướng dẫn tôi sử dụng OpenXML, nhưng tôi rất vui khi có một phím tắt để bắt đầu.
Brandon Barkley

1
Không vấn đề gì. Tôi vẫn sử dụng COM, nhưng chỉ trong những môi trường mà tôi có toàn quyền kiểm soát. Tôi đã sử dụng phương pháp OpenXML này trong một ứng dụng với vài trăm người dùng trong vài tháng và không gặp bất kỳ vấn đề nào so với lỗi hàng tuần với COM. Tôi cũng đã xem xét các giải pháp của bên thứ 3, giống như những giải pháp được đề cập ở đây, nhưng tôi thích tự viết nó để tôi có thể làm cho nó hiệu quả nhất có thể.
WATYF

0

Liên quan đến câu trả lời của tuncalik , thật tuyệt vời, đặc biệt nếu bạn muốn chơi một chút với mã :) nhưng nó đang đặt ngày của tôi vào Excel ở định dạng Mỹ, tức là ngày 2 tháng 3 năm 2014 ở Anh là ngày 2 tháng 3 năm 2014 nhưng tại Hoa Kỳ là 03/02/2014 với tháng đầu tiên, sau đó là ngày trong tuần sau đó. Tôi cần phải có nó ở định dạng Vương quốc Anh, bất kỳ ý tưởng xin vui lòng?

Tôi đã kiểm tra rằng nó được lưu trữ ở định dạng Vương quốc Anh trong DataTable của tôi và Excel của tôi cũng được đặt thành Vương quốc Anh nhưng vì một số lý do khi tạo tài liệu Excel, nó nghĩ là Hoa Kỳ (điều này có phải vì Microsoft là một công ty Hoa Kỳ :)

Tôi sẽ thử thử nghiệm với các mã văn hóa nhưng chưa chắc nên đặt nó ở đâu. Đã thử nhưng điều này không có tác dụng.

ps

Tôi đã phải thay đổi một dòng để nó hoạt động bằng cách thêm 'dàn diễn viên' như bên dưới

// single worksheet
Excel._Worksheet workSheet = (Excel._Worksheet)excelApp.ActiveSheet;

Cập nhật: Tôi đã đạt được định dạng ngày tháng ở Vương quốc Anh bằng cách chuyển đổi sang định dạng LongDateTime, mặc dù nó chỉ là một công việc xung quanh.

DateTime startDate = Convert.ToDateTime(myList[0].ToString());
string strStartDate = startDate.ToLongDateString();
DateTime endDate = Convert.ToDateTime(myList[myListTotalRows].ToString());
string strEndDate = endDate.ToLongDateString();    

hoan hô.


0

Bạn có thể sử dụng EasyXLS là một thư viện để xuất các tệp Excel.

Kiểm tra mã này:

DataSet ds = new DataSet();
ds.Tables.Add(dataTable);

ExcelDocument xls = new ExcelDocument();
xls.easy_WriteXLSFile_FromDataSet("datatable.xls", ds, 
           new ExcelAutoFormat(Styles.AUTOFORMAT_EASYXLS1), "DataTable");

Xem thêm mẫu này về cách xuất dữ liệu sang excel trong C # .


0

Chủ đề cũ - nhưng tôi nghĩ rằng tôi sẽ ném mã của mình vào đây. Tôi đã viết một hàm nhỏ để ghi một bảng dữ liệu vào một trang tính excel mới tại một đường dẫn (vị trí) được chỉ định. Ngoài ra, bạn sẽ cần thêm một tham chiếu đến thư viện microsoft excel 14.0.

Tôi đã lấy từ chủ đề này về cách viết bất cứ thứ gì vào excel - Cách ghi một số dữ liệu vào tệp excel (.xlsx)

tôi đã sử dụng nó để ngoại suy cách viết một dữ liệu có thể

* lưu ý trong các câu lệnh bắt tôi có tham chiếu lớp tĩnh của trình xử lý lỗi (bạn có thể bỏ qua chúng)

 using excel = Microsoft.Office.Interop.Excel;
 using System.IO;
 using System.Data;
 using System.Runtime.InteropServices;

 //class and namespace wrapper is not shown in this example 

 private void WriteToExcel(System.Data.DataTable dt, string location)
    {
        //instantiate excel objects (application, workbook, worksheets)
        excel.Application XlObj = new excel.Application();
        XlObj.Visible = false;
        excel._Workbook WbObj = (excel.Workbook)(XlObj.Workbooks.Add(""));
        excel._Worksheet WsObj = (excel.Worksheet)WbObj.ActiveSheet;

        //run through datatable and assign cells to values of datatable
        try
        {
            int row = 1; int col = 1;
            foreach (DataColumn column in dt.Columns)
            {
                //adding columns
                WsObj.Cells[row, col] = column.ColumnName;
                col++;
            }
            //reset column and row variables
            col = 1;
            row++;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                //adding data
                foreach (var cell in dt.Rows[i].ItemArray)
                {
                    WsObj.Cells[row, col] = cell;
                    col++;
                }
                col = 1;
                row++;
            }
            WbObj.SaveAs(location);
        }
        catch (COMException x)
        {                
            ErrorHandler.Handle(x);
        }
        catch (Exception ex)
        {               
            ErrorHandler.Handle(ex);
        }
        finally
        {
            WbObj.Close();                
        }
    }

1
Điều này hoạt động tốt, tuy nhiên, bạn không bao giờ giết bạn các quy trình Excel sau đó, vì vậy tôi khuyên bạn nên thêm điều này, thay thế SaveAsdòng của bạn vì nó được bao gồm ở đây: 'XlObj.DisplayAlerts = false; WbObj.SaveAs (vị trí); WbObj.Close (); XlObj.Quit (); Marshal.ReleaseComObject (WsObj); Marshal.ReleaseComObject (WbObj); Marshal.ReleaseComObject (XlObj); ' Để sử dụng Marshal.ReleaseComObjectphương pháp này, hãy thêm using System.Runtime.InteropServicesassembly vào dự án của bạn.
GrammatonCleric

0

Một cách thực hiện cũng sẽ là với Nhà cung cấp ACE OLEDB (xem thêm chuỗi kết nối cho Excel ). Tất nhiên, bạn phải cài đặt và đăng ký nhà cung cấp. Bạn nên có nó, nếu bạn đã cài đặt Excel, nhưng đây là điều bạn phải cân nhắc khi triển khai ứng dụng.

Đây là ví dụ về cách gọi phương thức trợ giúp từ ExportHelper:ExportHelper.CreateXlsFromDataTable(myDataTable, @"C:\tmp\export.xls");

Trình trợ giúp để xuất sang tệp Excel bằng ACE OLEDB:

public class ExportHelper
{
    private const string ExcelOleDbConnectionStringTemplate = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=YES\";";

    /// <summary>
    /// Creates the Excel file from items in DataTable and writes them to specified output file.
    /// </summary>
    public static void CreateXlsFromDataTable(DataTable dataTable, string fullFilePath)
    {
        string createTableWithHeaderScript = GenerateCreateTableCommand(dataTable);

        using (var conn = new OleDbConnection(String.Format(ExcelOleDbConnectionStringTemplate, fullFilePath)))
        {
            if (conn.State != ConnectionState.Open)
            {
                conn.Open();
            }

            OleDbCommand cmd = new OleDbCommand(createTableWithHeaderScript, conn);
            cmd.ExecuteNonQuery();

            foreach (DataRow dataExportRow in dataTable.Rows)
            {
                AddNewRow(conn, dataExportRow);
            }
        }
    }

    private static void AddNewRow(OleDbConnection conn, DataRow dataRow)
    {
        string insertCmd = GenerateInsertRowCommand(dataRow);

        using (OleDbCommand cmd = new OleDbCommand(insertCmd, conn))
        {
            AddParametersWithValue(cmd, dataRow);
            cmd.ExecuteNonQuery();
        }
    }

    /// <summary>
    /// Generates the insert row command.
    /// </summary>
    private static string GenerateInsertRowCommand(DataRow dataRow)
    {
        var stringBuilder = new StringBuilder();
        var columns = dataRow.Table.Columns.Cast<DataColumn>().ToList();
        var columnNamesCommaSeparated = string.Join(",", columns.Select(x => x.Caption));
        var questionmarkCommaSeparated = string.Join(",", columns.Select(x => "?"));

        stringBuilder.AppendFormat("INSERT INTO [{0}] (", dataRow.Table.TableName);
        stringBuilder.Append(columnNamesCommaSeparated);
        stringBuilder.Append(") VALUES(");
        stringBuilder.Append(questionmarkCommaSeparated);
        stringBuilder.Append(")");
        return stringBuilder.ToString();
    }

    /// <summary>
    /// Adds the parameters with value.
    /// </summary>
    private static void AddParametersWithValue(OleDbCommand cmd, DataRow dataRow)
    {
        var paramNumber = 1;

        for (int i = 0; i <= dataRow.Table.Columns.Count - 1; i++)
        {
            if (!ReferenceEquals(dataRow.Table.Columns[i].DataType, typeof(int)) && !ReferenceEquals(dataRow.Table.Columns[i].DataType, typeof(decimal)))
            {
                cmd.Parameters.AddWithValue("@p" + paramNumber, dataRow[i].ToString().Replace("'", "''"));
            }
            else
            {
                object value = GetParameterValue(dataRow[i]);
                OleDbParameter parameter = cmd.Parameters.AddWithValue("@p" + paramNumber, value);
                if (value is decimal)
                {
                    parameter.OleDbType = OleDbType.Currency;
                }
            }

            paramNumber = paramNumber + 1;
        }
    }

    /// <summary>
    /// Gets the formatted value for the OleDbParameter.
    /// </summary>
    private static object GetParameterValue(object value)
    {
        if (value is string)
        {
            return value.ToString().Replace("'", "''");
        }
        return value;
    }

    private static string GenerateCreateTableCommand(DataTable tableDefination)
    {
        StringBuilder stringBuilder = new StringBuilder();
        bool firstcol = true;

        stringBuilder.AppendFormat("CREATE TABLE [{0}] (", tableDefination.TableName);

        foreach (DataColumn tableColumn in tableDefination.Columns)
        {
            if (!firstcol)
            {
                stringBuilder.Append(", ");
            }
            firstcol = false;

            string columnDataType = "CHAR(255)";

            switch (tableColumn.DataType.Name)
            {
                case "String":
                    columnDataType = "CHAR(255)";
                    break;
                case "Int32":
                    columnDataType = "INTEGER";
                    break;
                case "Decimal":
                    // Use currency instead of decimal because of bug described at 
                    // http://social.msdn.microsoft.com/Forums/vstudio/en-US/5d6248a5-ef00-4f46-be9d-853207656bcc/localization-trouble-with-oledbparameter-and-decimal?forum=csharpgeneral
                    columnDataType = "CURRENCY";
                    break;
            }

            stringBuilder.AppendFormat("{0} {1}", tableColumn.ColumnName, columnDataType);
        }
        stringBuilder.Append(")");

        return stringBuilder.ToString();
    }
}

0

sử dụng lớp sau

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using excel = Microsoft.Office.Interop.Excel;
using EL = ExcelLibrary.SpreadSheet;
using System.Drawing;
using System.Collections;
using System.Runtime.InteropServices;
using System.Windows.Forms;


namespace _basic
{
public class ExcelProcesser
{
    public void WriteToExcel(System.Data.DataTable dt)
    {
        excel.Application XlObj = new excel.Application();
        XlObj.Visible = false;
        excel._Workbook WbObj = (excel.Workbook)(XlObj.Workbooks.Add(""));
        excel._Worksheet WsObj = (excel.Worksheet)WbObj.ActiveSheet;
        object misValue = System.Reflection.Missing.Value;


        try
        {
            int row = 1; int col = 1;
            foreach (DataColumn column in dt.Columns)
            {
                //adding columns
                WsObj.Cells[row, col] = column.ColumnName;
                col++;
            }
            //reset column and row variables
            col = 1;
            row++;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                //adding data
                foreach (var cell in dt.Rows[i].ItemArray)
                {
                    WsObj.Cells[row, col] = cell;
                    col++;
                }
                col = 1;
                row++;
            }
            WbObj.SaveAs(fileFullName, excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            WbObj.Close(true, misValue, misValue);
        }
    }
}

}


0

Giải pháp này về cơ bản là đẩy List<Object>dữ liệu sang Excel, Nó sử dụng DataTable để đạt được điều này, tôi đã triển khai một phương pháp mở rộng, vì vậy về cơ bản có hai điều cần thiết. 1. Một Phương pháp Mở rộng.

public static class ReportHelper
{
    public static string ToExcel<T>(this IList<T> data)
    {
        PropertyDescriptorCollection properties =
            TypeDescriptor.GetProperties(typeof(T));
        DataTable table = new DataTable();
        foreach (PropertyDescriptor prop in properties)
        {
            //table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
            if (prop.Attributes[typeof(FGMS.Entity.Extensions.ReportHeaderAttribute)] != null)
            {
                table.Columns.Add(GetColumnHeader(prop), Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
            }
        }

        //So it seems like when there is only one row of data the headers do not appear
        //so adding a dummy blank row which fixed the issues
        //Add a blank Row - Issue # 1471
        DataRow blankRow = table.NewRow();
        table.Rows.Add(blankRow);

        foreach (T item in data)
        {
            DataRow row = table.NewRow();
            foreach (PropertyDescriptor prop in properties)
                //row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
                if (prop.Attributes[typeof(FGMS.Entity.Extensions.ReportHeaderAttribute)] != null)
                {
                    row[GetColumnHeader(prop)] = prop.GetValue(item) ?? DBNull.Value;
                }
            table.Rows.Add(row);
        }
        table.TableName = "Results";
        var filePath = System.IO.Path.GetTempPath() + "\\" + System.Guid.NewGuid().ToString() + ".xls";
        table.WriteXml(filePath);

        return filePath;
    }

    private static string GetColumnHeader(PropertyDescriptor prop)
    {
        return ((FGMS.Entity.Extensions.ReportHeaderAttribute)(prop.Attributes[typeof(FGMS.Entity.Extensions.ReportHeaderAttribute)])).ReportHeaderText;
    }       
}
  1. Trang trí các lớp DTO của bạn với Thuộc tính [ReportHeaderAttribute("Column Name")]
public class UserDTO
    {
        public int Id { get; set; }
        public int SourceId { get; set; }
        public string SourceName { get; set; }

        [ReportHeaderAttribute("User Type")]
        public string UsereType { get; set; }

        [ReportHeaderAttribute("Address")]
        public string Address{ get; set; }

        [ReportHeaderAttribute("Age")]
        public int Age{ get; set; }

        public bool IsActive { get; set; }

        [ReportHeaderAttribute("Active")]
        public string IsActiveString
        {
            get
            {
                return IsActive ? "Yes" : "No";
            }
        }}

Mọi thứ cần trở thành một cột trong Excel phải được trang trí bằng [ReportHeaderAttribute("Column Name")]

Sau đó, Đơn giản

Var userList = Service.GetUsers() //Returns List of UserDTO;
var excelFilePath = userList.ToExcel();

HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
            var stream = new FileStream(excelFilePath, FileMode.Open);
            result.Content = new StreamContent(stream);
            result.Content.Headers.ContentType =
                new MediaTypeHeaderValue("application/vnd.ms-excel");
            result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "UserList.xls" };

            return result;

và nếu op không muốn tạo DTO cho mọi bảng họ sẽ chạy điều này với? Ví dụ như foreach trong số 1 nghìn bảng của tôi làm điều này. Việc thêm thuộc tính tiêu đề báo cáo không được thực hiện ngay - rất nhiều mã ở đó và điều đó trước cả khi thực hiện công việc thực. Không loại bỏ giải pháp của bạn - chỉ chỉ ra rằng nguyên tắc lười biếng không được sử dụng ở đây vì giải pháp này thêm bước tạo dto's và sau đó biên dịch .. Tôi nên nói - Tôi thích rằng bạn đã sử dụng generics.
Ken

0

Để xuất dữ liệu sang Excel, bạn có thể sử dụng thư viện ClosedXML.Report ( https://github.com/ClosedXML/ClosedXML.Report ). Tin tôi đi, đây là một thư viện tuyệt vời và dễ dàng cho cô ấy sử dụng. Thư viện không cần Excel Interop. ClosedXML.Report tạo tệp Excel dựa trên mẫu mà bạn có thể tạo trong Excel bằng bất kỳ định dạng nào. Ví dụ:

    var template = new XLTemplate(@".\Templates\report.xlsx");

    using (var db = new DbDemos())
    {
        var cust = db.customers.LoadWith(c => c.Orders).First();
        template.AddVariable(cust);
        template.Generate();
    }

    template.SaveAs(outputFile);

0
Private tmr As System.Windows.Forms.Timer

Private Sub TestExcel() Handles Button1.Click

    '// Initial data: SQL Server table with 6 columns and 293000 rows.


    '// Data table holding all data
    Dim dt As New DataTable("F161")

    '// Create connection
    Dim conn As New SqlConnection("Server=MYSERVER;Database=Test;Trusted_Connection=Yes;")
    Dim fAdapter As New SqlDataAdapter With
    {
        .SelectCommand = New SqlCommand($"SELECT * FROM dbo.MyTable", conn)
    }

    '// Fill DataTable
    fAdapter.Fill(dt)

    '// Create Excel application
    Dim xlApp As New Excel.Application With {.Visible = True}

    '// Temporarily disable screen updating
    xlApp.ScreenUpdating = False

    '// Create brand new workbook
    Dim xlBook As Excel.Workbook = xlApp.Workbooks.Add()
    Dim xlSheet As Excel.Worksheet = DirectCast(xlBook.Sheets(1), Excel.Worksheet)

    '// Get number of rows
    Dim rows_count = dt.Rows.Count
    '// Get number of columns
    Dim cols_count = dt.Columns.Count

    '// Here 's the core idea: after receiving data
    '// you need to create an array and transfer it to sheet.
    '// Why array?
    '// Because it's the fastest way to transfer data to Excel's sheet.
    '// So, we have two tasks:
    '// 1) Create array
    '// 2) Transfer array to sheet

    '// =========================================================
    '// TASK 1: Create array
    '// =========================================================
    '// In order to create array, we need to know that
    '// Excel's Range object expects 2-D array whose lower bounds
    '// of both dimensions start from 1.
    '// This means you can't use C# array.
    '// You need to manually create such array.
    '// Since we already calculated number of rows and columns,
    '// we can use these numbers in creating array.
    Dim arr = Array.CreateInstance(GetType(Object), {rows_count, cols_count}, {1, 1})

    '// Fill array
    For r = 0 To rows_count - 1
        For c = 0 To cols_count - 1
            arr(r + 1, c + 1) = dt.Rows(r)(c)
        Next
    Next

    '// =========================================================
    '// TASK 2: Transfer array to sheet
    '// =========================================================
    '// Now we need to transfer array to sheet.
    '// So, how transfer array to sheet fast?
    '// 
    '// THE FASTEST WAY TO TRANSFER DATA TO SHEET IS TO ASSIGN ARRAY TO RANGE.
    '// We could, of course, hard-code values, but Resize property
    '// makes this work a breeze:
    xlSheet.Range("A1").Resize.Resize(rows_count, cols_count).Value = arr

    '// If we decide to dump data by iterating over array,
    '// it will take LOTS of time.
    '// For r = 1 To rows_count
    '//     For c = 1 To cols_count
    '//         xlSheet.Cells(r, c) = arr(r, c)
    '//     Next
    '// Next

    '// Here are time results:
    '// 1) Assigning array to Range: 3 seconds
    '// 2) Iterating over array: 45 minutes

    '// Turn updating on
    xlApp.ScreenUpdating = True
    xlApp = Nothing
    xlBook = Nothing
    xlSheet = Nothing

    '// Here we have another problem:
    '// creating array took lots of memory (about 150 MB).
    '// Using 'GC.Collect()', by unknown reason, doesn't help here.
    '// However, if you run GC.Collect() AFTER this procedure is finished
    '// (say, by pressing another button and calling another procedure),
    '// then the memory is cleaned up.
    '// I was wondering how to avoid creating some extra button to just release memory,
    '// so I came up with the idea to use timer to call GC.
    '// After 2 seconds GC collects all generations.
    '// Do not forget to dispose timer since we need it only once.

    tmr = New Timer()
    AddHandler tmr.Tick,
        Sub()
            GC.Collect()
            GC.WaitForPendingFinalizers()
            GC.WaitForFullGCComplete()
            tmr.Dispose()
        End Sub
    tmr.Interval = TimeSpan.FromSeconds(2).TotalMilliseconds()
    tmr.Start()

End Sub

0

Mã mẫu hoàn toàn (trong trường hợp nó có thể giúp ai đó có một số ý tưởng), dựa trên câu trả lời của Tomasz Wiśniewski từ đây: https://stackoverflow.com/a/21079709/2717521

MainWindow ExportButton:

public int counter;

public void SaveToExcel(object sender, RoutedEventArgs e)
{
    counter = 1;
    CountChecker();
}

public void CountChecker()
{
    string filename = GlobalStrings.building_house_address;
    string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\";


    if (CurrentID != 0)
    {
        if (!File.Exists(path + filename + ".xlsx"))
        {
            DataGridParts.Export(path + filename);
            MessageBoxEx.Show(this, "Shranjeno na namizje");
        }
        else
        {
            if (!File.Exists(path + "\\" + filename + " (" + (counter) + ")" + ".xlsx"))
            {
                DataGridParts.Export(path + filename + " (" + (counter) + ")");
                MessageBoxEx.Show(this, "Shranjeno na namizje");
            }
            else
            {
                counter++;
                CountChecker();
            }
        }
    }
    else
    {
        MessageBoxEx.Show(this, "Izbran ni noben naslov!");
    }
}

Lớp ExportToExcel:

using Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;

namespace CBUGIS
{
    public static class ExportToExcel
    {
        /// <summary>
        /// Export DataTable to Excel file
        /// </summary>
        /// <param name="DataTable">Source DataTable</param>
        /// <param name="ExcelFilePath">Path to result file name</param>
        public static void Export(this System.Data.DataTable DataTable, string ExcelFilePath = null)
        {
            int ColumnsCount;
            int RowShift = 5;

            ColumnsCount = DataTable.Columns.Count;

            // load excel, and create a new workbook
            Application Excel = new Application();
            Excel.Workbooks.Add();

            // single worksheet
            _Worksheet Worksheet = Excel.ActiveSheet;
            Excel.Sheets[1].Name = "CBUGIS";

            Worksheet.Columns.NumberFormat = "@";
            Worksheet.Columns.HorizontalAlignment = XlHAlign.xlHAlignLeft;

            object[,] Title = new object[3, 1]; // Array Size

            if (GlobalStrings.building_alterantive_addresses.Length == 0)
            {
                if (GlobalStrings.building_postcode.Length != 0)
                {
                    Title[0, 0] = "NASLOV: " + GlobalStrings.building_house_street + " " + GlobalStrings.building_house_number + GlobalStrings.building_house_id + ", " + GlobalStrings.building_postcode + " " + GlobalStrings.building_area;
                    Title[1, 0] = "K.O.: " + GlobalStrings.building_cadastral_community + ", ŠT.STAVBE: " + GlobalStrings.building_building_number + ", ŠT.PARCELE: " + GlobalStrings.building_plot_number;
                }
                else
                {
                    Title[0, 0] = "NASLOV: " + GlobalStrings.building_house_street + " " + GlobalStrings.building_house_number + GlobalStrings.building_house_id;
                    Title[1, 0] = "K.O.: " + GlobalStrings.building_cadastral_community + ", ŠT.STAVBE: " + GlobalStrings.building_building_number + ", " + GlobalStrings.building_plot_number;
                }
            }
            else
            {
                if (GlobalStrings.building_postcode.Length != 0)
                {
                    Title[0, 0] = "NASLOV: " + GlobalStrings.building_house_street + " " + GlobalStrings.building_house_number + GlobalStrings.building_house_id + ", " + GlobalStrings.building_postcode + " " + GlobalStrings.building_area;
                    Title[1, 0] = "K.O.: " + GlobalStrings.building_cadastral_community + ", ŠT.STAVBE: " + GlobalStrings.building_building_number + ", ŠT.PARCELE: " + GlobalStrings.building_plot_number;
                    Title[2, 0] = "GLEJ TUDI: " + GlobalStrings.building_alterantive_addresses;
                }
                else
                {
                    Title[0, 0] = "NASLOV: " + GlobalStrings.building_house_street + " " + GlobalStrings.building_house_number + GlobalStrings.building_house_id;
                    Title[1, 0] = "K.O.: " + GlobalStrings.building_cadastral_community + ", ŠT.STAVBE: " + GlobalStrings.building_building_number + ", ŠT.PARCELE: " + GlobalStrings.building_plot_number;
                    Title[2, 0] = "GLEJ TUDI: " + GlobalStrings.building_alterantive_addresses;
                }
            }

            Range TitleRange = Worksheet.get_Range((Range)(Worksheet.Cells[3, 1]), (Range)(Worksheet.Cells[1, 1]));
            TitleRange.Value = Title;
            TitleRange.Font.Bold = true;
            TitleRange.Font.Size = 10;


            object[] Header = new object[11]; // Number of Columns

            Header[0] = "DEL";
            Header[1] = "DELEŽ";
            Header[2] = "CRP";
            Header[3] = "LASTNIK";
            Header[4] = "NASLOV";
            Header[5] = "P.Š";
            Header[6] = "OBMOČJE";
            Header[7] = "DRŽAVA";
            Header[8] = "EMŠO/MAT. ŠT.";
            Header[9] = "OPIS";
            Header[10] = "OPOMBA";

            Range HeaderRange = Worksheet.get_Range((Range)(Worksheet.Cells[RowShift, 2]), (Range)(Worksheet.Cells[RowShift, 12]));
            HeaderRange.Value = Header;
            HeaderRange.Font.Bold = true;
            HeaderRange.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightGray);

            // DataCells
            int RowsCount = DataTable.Rows.Count;

            object[,] Cells = new object[RowsCount, ColumnsCount];

            for (int j = 0; j < RowsCount; j++)
                for (int i = 0; i < ColumnsCount - 1; i++)
                    if (i > 1)
                    {
                        Cells[j, i - 2] = DataTable.Rows[j][i];
                    }

            Range CellRange = Worksheet.get_Range((Range)(Worksheet.Cells[RowShift +1, 2]), (Range)(Worksheet.Cells[RowShift + RowsCount, 12]));
            CellRange.Value = Cells;
            CellRange.Borders.LineStyle = XlLineStyle.xlContinuous;

            Worksheet.Columns.NumberFormat = "@";
            Worksheet.Columns[1].ColumnWidth = 0.1;
            for (int b = 1; b < 12; b++)
            {
                if (b > 1)
                {
                    Worksheet.Columns[b].AutoFit();
                }
            }

            Worksheet.PageSetup.Orientation = XlPageOrientation.xlLandscape;
            Worksheet.PageSetup.TopMargin = 0.5;
            Worksheet.PageSetup.BottomMargin = 0.5;
            Worksheet.PageSetup.RightMargin = 0.5;
            Worksheet.PageSetup.LeftMargin = 0.5;

            // check fielpath
            if (ExcelFilePath != null && ExcelFilePath != "")
            {
                Worksheet.SaveAs(ExcelFilePath);
                Excel.Quit();
                Marshal.FinalReleaseComObject(Worksheet);
                Marshal.FinalReleaseComObject(TitleRange);
                Marshal.FinalReleaseComObject(HeaderRange);
                Marshal.FinalReleaseComObject(CellRange);
                Marshal.FinalReleaseComObject(Excel);
            }
            else

            // no filepath is given
            {
                Excel.Visible = true;
            }      
        }
    }
}

0

Với gói EPPlus NuGet, điều đó rất dễ dàng .

public class TestObject
{
    public int Col1 { get; set; }
    public int Col2 { get; set; }
    public string Col3 { get; set; }
    public DateTime Col4 { get; set; }
}

[TestMethod]
public void LoadFromCollection_MemberList_Test()
{
    ///programming/32587834/epplus-loadfromcollection-text-converted-to-number/32590626#32590626

    var TestObjectList = new List<TestObject>();
    for (var i = 0; i < 10; i++)
        TestObjectList.Add(new TestObject {Col1 = i, Col2 = i*10, Col3 = (i*10) + "E4"});

    //Create a test file
    var fi = new FileInfo(@"c:\temp\LoadFromCollection_MemberList_Test.xlsx");
    if (fi.Exists)
        fi.Delete();

    using (var pck = new ExcelPackage(fi))
    {
        //Do NOT include Col1
        var mi = typeof (TestObject)
            .GetProperties()
            .Where(pi => pi.Name != "Col1")
            .Select(pi => (MemberInfo)pi)
            .ToArray();

        var worksheet = pck.Workbook.Worksheets.Add("Sheet1");
        worksheet.Cells.LoadFromCollection(
            TestObjectList
            , true
            , TableStyles.Dark1
            , BindingFlags.Public| BindingFlags.Instance
            , mi);

        pck.Save();
    }
}

Lưu ý rằng Col1KHÔNG có trong đầu ra:

nhập mô tả hình ảnh ở đây

Khi sử dụng trang web của chúng tôi, bạn xác nhận rằng bạn đã đọc và hiểu Chính sách cookieChính sách bảo mật của chúng tôi.
Licensed under cc by-sa 3.0 with attribution required.