source

Excel 파일(.xlsx)에 데이터를 쓰는 방법

bestscript 2023. 5. 20. 22:51

Excel 파일(.xlsx)에 데이터를 쓰는 방법

이것이 제가 하려는 일입니다.

  1. 이름 + 값(날짜)을 사용하여 Excel 파일(.xlsx) c://test/files/work1_4.13.14.xlsx를 만듭니다.

    예제: work1_4.13.14.xlsx

  2. 파일에 헤더를 설정합니다.

    예: [이름] [나이] [도시]

  3. 저는 3개가 있습니다.List<string>이름, 나이, 도시가 포함된 오브젝트를 Excel 시트에 작성해야 합니다.

다음과 같은 형식으로 데이터를 지정합니다.

Name   Age  City
Ben    20   xyz
Jack   25   xyz
Mike   45   zyx

이 형식으로 엑셀 시트에 데이터를 어떻게 보낼 수 있습니까?

이 코드를 사용해 보십시오.

Microsoft.Office.Interop.Excel.Application oXL;
Microsoft.Office.Interop.Excel._Workbook oWB;
Microsoft.Office.Interop.Excel._Worksheet oSheet;
Microsoft.Office.Interop.Excel.Range oRng;
object misvalue = System.Reflection.Missing.Value;
try
{
    //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;

    //Add table headers going cell by cell.
    oSheet.Cells[1, 1] = "First Name";
    oSheet.Cells[1, 2] = "Last Name";
    oSheet.Cells[1, 3] = "Full Name";
    oSheet.Cells[1, 4] = "Salary";

    //Format A1:D1 as bold, vertical alignment = center.
    oSheet.get_Range("A1", "D1").Font.Bold = true;
    oSheet.get_Range("A1", "D1").VerticalAlignment =
        Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;

    // Create an array to multiple values at once.
    string[,] saNames = new string[5, 2];

    saNames[0, 0] = "John";
    saNames[0, 1] = "Smith";
    saNames[1, 0] = "Tom";

    saNames[4, 1] = "Johnson";

    //Fill A2:B6 with an array of values (First and Last Names).
    oSheet.get_Range("A2", "B6").Value2 = saNames;

    //Fill C2:C6 with a relative formula (=A2 & " " & B2).
    oRng = oSheet.get_Range("C2", "C6");
    oRng.Formula = "=A2 & \" \" & B2";

    //Fill D2:D6 with a formula(=RAND()*100000) and apply format.
    oRng = oSheet.get_Range("D2", "D6");
    oRng.Formula = "=RAND()*100000";
    oRng.NumberFormat = "$0.00";

    //AutoFit columns A:D.
    oRng = oSheet.get_Range("A1", "D1");
    oRng.EntireColumn.AutoFit();

    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);

    oWB.Close();
    oXL.Quit();

    //...

ClosedX를 사용할 수 있습니다.이것을 위한 ML.

테이블을 데이터 테이블에 저장하면 다음과 같은 간단한 스니펫으로 테이블을 내보낼 수 있습니다.

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

ClosedX의 설명서를 읽을 수 있습니다.자세한 내용은 ML.이것이 도움이 되길 바랍니다!

여기에 우리가 찾고 있는 것이 정확히 있기를 바랍니다.

private void button2_Click(object sender, RoutedEventArgs e)
{
    UpdateExcel("Sheet3", 4, 7, "Namachi@gmail");
}

private void UpdateExcel(string sheetName, int row, int col, string data)
{
    Microsoft.Office.Interop.Excel.Application oXL = null;
    Microsoft.Office.Interop.Excel._Workbook oWB = null;
    Microsoft.Office.Interop.Excel._Worksheet oSheet = null;

    try
    {
        oXL = new Microsoft.Office.Interop.Excel.Application();
        oWB = oXL.Workbooks.Open("d:\\MyExcel.xlsx");
        oSheet = String.IsNullOrEmpty(sheetName) ? (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet : (Microsoft.Office.Interop.Excel._Worksheet)oWB.Worksheets[sheetName];

        oSheet.Cells[row, col] = data;

        oWB.Save();

        MessageBox.Show("Done!");
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
    finally
    {
        if (oWB != null)
        oWB.Close();
    }
}

Excel 파일을 열지 않고도 파일에 쓸 수 있습니다.Microsoft.Jet.OLEDB.4.0그리고.OleDb.사용.OleDbSQL을 사용하여 테이블에 쓰는 것처럼 동작합니다.

이것은 제가 새로운 엑셀 파일을 만들고 쓸 때 사용한 코드입니다.추가 참조가 필요하지 않습니다.

var connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\SomePath\ExcelWorkBook.xls;Extended Properties=Excel 8.0";
using (var excelConnection = new OleDbConnection(connectionString))
{
    // The excel file does not need to exist, opening the connection will create the
    // excel file for you
    if (excelConnection.State != ConnectionState.Open) { excelConnection.Open(); }

    // data is an object so it works with DBNull.Value
    object propertyOneValue = "cool!";
    object propertyTwoValue = "testing";

    var sqlText = "CREATE TABLE YourTableNameHere ([PropertyOne] VARCHAR(100), [PropertyTwo] INT)";

    // Executing this command will create the worksheet inside of the workbook
    // the table name will be the new worksheet name
    using (var command = new OleDbCommand(sqlText, excelConnection)) { command.ExecuteNonQuery(); }

    // Add (insert) data to the worksheet
    var commandText = $"Insert Into YourTableNameHere ([PropertyOne], [PropertyTwo]) Values (@PropertyOne, @PropertyTwo)";

    using (var command = new OleDbCommand(commandText, excelConnection))
    {
        // We need to allow for nulls just like we would with
        // sql, if your data is null a DBNull.Value should be used
        // instead of null 
        command.Parameters.AddWithValue("@PropertyOne", propertyOneValue ?? DBNull.Value);
        command.Parameters.AddWithValue("@PropertyTwo", propertyTwoValue ?? DBNull.Value);

        command.ExecuteNonQuery();
    }
}

최근에 npoi를 해봤는데 아주 간단했습니다.

요청하신 대로, 데이터를 출력하는 코드를 만듭시다.work1_4.13.14.xlsx다음과 같은 파일:

Name   Age  City
Ben    20   xyz
Jack   25   xyz
Mike   45   zyx

여기 코드가 있습니다.

using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.IO;

namespace ExcelWriter
{
    class Program
    {
        static void Main(string[] args)
        {
            IWorkbook workbook = new XSSFWorkbook();
            ISheet sheet1 = workbook.CreateSheet("Sheet1");

            IRow row1 = sheet1.CreateRow(0);
            row1.CreateCell(0).SetCellValue("Name");
            row1.CreateCell(1).SetCellValue("Age");
            row1.CreateCell(2).SetCellValue("City");

            IRow row2 = sheet1.CreateRow(1);
            row2.CreateCell(0).SetCellValue("Ben");
            row2.CreateCell(1).SetCellValue("20");
            row2.CreateCell(2).SetCellValue("xyz");

            IRow row3 = sheet1.CreateRow(2);
            row3.CreateCell(0).SetCellValue("Jack");
            row3.CreateCell(1).SetCellValue("25");
            row3.CreateCell(2).SetCellValue("xyz");

            IRow row4 = sheet1.CreateRow(3);
            row4.CreateCell(0).SetCellValue("Mike");
            row4.CreateCell(1).SetCellValue("45");
            row4.CreateCell(2).SetCellValue("zyx");

            FileStream sw = File.Create("work1_4.13.14.xlsx");
            workbook.Write(sw);
            sw.Close();
        }
    }
}

초보자가 이해하기 쉽도록 루프를 사용한 것은 아닙니다.

.CreateRow(int index)지정된 인덱스에 새 행을 만듭니다.
row.CreateCell(int index)행의 지정된 인덱스에 새 셀을 만듭니다.
cell.SetCellValue(string value)행 인덱스에 값을 설정합니다.

자세히 알아보기:

Nuget: https://www.nuget.org/packages/NPOI
코드: https://github.com/nissl-lab/npoi
예: https://github.com/nissl-lab/npoi-examples

.Net 7과 NuGet Package EP Plus를 사용하여 다음 코드를 사용하여 OP에서 요청한 Excel 파일을 만들 수 있습니다.

콘솔 응용 프로그램을 만들고 다음에 씁니다.Program.cs다음 파일을 작성:

using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.IO;

ExcelPackage.LicenseContext = LicenseContext.NonCommercial;

List<string>[] users =
{
    new()
    {
        "Ben",
        "20",
        "xyz"
    },
    new()
    {
        "Jack",
        "25",
        "xyz"
    },
    new()
    {
        "Mike",
        "45",
        "zyx"
    }
};

//change to your desired directory
string dir = @"C:\Users\user\Desktop\";
string name = "work";
string extension = ".xlsx";
string fileName = $"{name}_{DateTime.Today:d.M.yy}{extension}";
string path = Path.Combine(dir, fileName);

//Create a new file (if none exists at this path)
FileInfo excel = new(path);

//Using this next statement makes sure you end the process when its not needed
using ExcelPackage package = new ExcelPackage(excel);

//Create a new worksheet
ExcelWorksheet worksheetWork = package.Workbook.Worksheets.Add("Work");

//Create the headers by cell name
worksheetWork.Cells["A1"].Value = "Name";
worksheetWork.Cells["B1"].Value = "Age";
worksheetWork.Cells["C1"].Value = "City";

for (int row = 0; row < users.Length; row++)
{
    for (int column = 0; column < 3; column++)
    {
        //Add the required values to cells by row and column
        //rows and columns start from 1, in this example we need to add 1 to both,
        //and an extra 1 to row to account for the header.
        if (column is 1) //Age column
        {
             worksheetWork.Cells[row + 2, column + 1].Value = int.Parse(users[row][column]);
        }
        else
        {
             worksheetWork.Cells[row + 2, column + 1].Value = users[row][column];
        }
    }
}

package.Save();

프로그램이 실행되면 스크린샷에 표시된 대로 파일이 생성됩니다.

산출량

다음 단계를 수행합니다.

//Excel을 시작하고 응용 프로그램 개체를 가져옵니다.

oXL = new Microsoft.Office.Interop.Excel.Application();

oXL.Visible = false;

언급URL : https://stackoverflow.com/questions/23041021/how-to-write-some-data-to-excel-file-xlsx