简体   繁体   English

从特定列 C# 将数据表导出到 Excel Strat

[英]Export Datatable into Excel Strat from Specific Column C#

I have a datatable and I want export the data into excel but start exporting from a specific column.我有一个数据表,我想将数据导出到 excel 但开始从特定列导出。 Scenario, I have an excel sheet and first 5 columns [AE] have data and want to export from datatable and should start from coloumn-F.场景,我有一张 excel 表,前 5 列 [AE] 有数据,想从数据表中导出,应该从列-F 开始。 How to achieve this in C# console application.如何在 C# 控制台应用程序中实现这一点。

So, the most obvious approach here would be to iterate over the data table's rows and write each to the Excel sheet manually:因此,这里最明显的方法是遍历数据表的行并将每个行手动写入 Excel 表:

Microsoft.Office.Interop.Excel.Application oXL;
Microsoft.Office.Interop.Excel._Workbook oWB;
Microsoft.Office.Interop.Excel._Worksheet oSheet;

// Start Excel and get Application object.
oXL = new Microsoft.Office.Interop.Excel.Application();
oXL.Visible = true;

// Get a new workbook.
oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Add(""));
oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet;

// Write the data. Remember that Excel is 1-indexed
int rowIndex = 1;
foreach (DataRow row in table.Rows) {
    int colIndex = 6;
    foreach (DataColumn col in table.Columns) {
        oSheet.Cells[rowIndex, colIndex] = row[col];
        colIndex++;
    }

    rowIndex++;
}

// Save the Excel file
oXL.Visible = false;
oXL.UserControl = false;
oWB.SaveAs("c:\\test\\test505.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing,
    false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
    Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

// Exit Excel
oWB.Close();
oXL.Quit();

There's probably a more elegant solution to this problem but I think this will get the job done, at least.这个问题可能有一个更优雅的解决方案,但我认为这至少可以完成工作。 As a reference, my Excel code was modified from this question , so you might be able to find a better match for your specific needs there.作为参考,我的 Excel 代码是从这个问题修改的,因此您可能可以在那里找到更适合您特定需求的匹配项。

you can use ClosedXML library.您可以使用 ClosedXML 库。 example from my code我的代码中的示例

        var wb = new XLWorkbook();
        var ws = wb.Worksheets.Add("My Sheet 1");

        ws.Cell("A8").Value = "Print by Admin:";
        ws.Cell("B8").Value = $"{GetUserById(userId).name} - {GetUserById(userId).position_name}";
        ws.Range("B8:C8").Merge();

        var range = ws.Cell("B12").InsertTable(data);
        range.Style.Border.TopBorder = XLBorderStyleValues.Thin;
        range.Style.Border.LeftBorder = XLBorderStyleValues.Thin;
        range.Style.Border.RightBorder = XLBorderStyleValues.Thin;
        range.Style.Border.BottomBorder = XLBorderStyleValues.Thin;

        ws.Row(12).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
        ws.Row(12).Style.Font.Bold = true;

        MemoryStream stream = (MemoryStream)GetStream(wb);

        return File(stream.ToArray(), ""application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"", "yourfilename.xlsx");

here code for Getstream:这里 Getstream 的代码:

public Stream GetStream(XLWorkbook excelWorkbook)
        {
            Stream fs = new MemoryStream();
            excelWorkbook.SaveAs(fs);
            fs.Position = 0;
            return fs;
        }

Alternatively, you could try using the ClosedXML library:或者,您可以尝试使用ClosedXML库:

XLWorkbook workbook = new XLWorkbook();
DataTable table = GetYourTable();
var sheet = workbook.Worksheets.Add(table);

var firstColumn = sheet.Column(1);
firstColumn.InsertColumnsBefore(5);

This code works by creating a new Excel worksheet from the datatable, getting a pointer to the first column in the worksheet and then inserting five columns (A - E) before it.此代码通过从数据表中创建一个新的 Excel 工作表来工作,获取指向工作表中第一列的指针,然后在它之前插入五列 (A - E)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM