Microsoft Office를 설치하지 않고 C#에서 Excel (.xls 및 .xlsx) 파일을 어떻게 작성합니까? [닫은

StackOverflow https://stackoverflow.com/questions/151005

  •  02-07-2019
  •  | 
  •  

문제

코드를 실행중인 시스템에 Excel을 설치하지 않고 C#으로 Excel 스프레드 시트를 어떻게 만들 수 있습니까?

도움이 되었습니까?

해결책

Excellibrary라는 라이브러리를 사용할 수 있습니다. Google 코드에 게시 된 무료 오픈 소스 라이브러리입니다.

Excellibrary

이것은 위에서 언급 한 PHP 엑셀 라이터의 포트로 보입니다. 아직 새로운 .xlsx 형식으로 작성되지는 않지만 해당 기능을 추가하기 위해 노력하고 있습니다.

매우 간단하고 작고 사용하기 쉽습니다. 또한 데이터 세트와 데이터 타이블을 사용하여 Excel 데이터로 쉽게 작업 할 수있는 DataSelper가 있습니다.

Excellibrary는 여전히 구형 Excel 형식 (.xls 파일)에만 효과가있는 것으로 보이지만 향후 최신 2007/2010 형식에 대한 지원을 추가 할 수 있습니다.

당신은 또한 사용할 수 있습니다 epplus, Excel 2007/2010 형식 파일 (.xlsx 파일)에만 작동합니다. 또한 있습니다 NPOI 둘 다와 함께 작동합니다.

주석에 언급 된 것처럼 각 라이브러리에는 알려진 몇 가지 버그가 있습니다. 대체로, Epplus는 시간이 지남에 따라 최선의 선택 인 것 같습니다. 더 적극적으로 업데이트되고 문서화 된 것 같습니다.

또한 아래의 @артёарионов가 언급 한 바와 같이, Epplus는 피벗 테이블에 대한 지원을 제공하며 Excellibrary는 약간의 지원을받을 수 있습니다 (Excellibrary의 피벗 테이블 문제)

다음은 빠른 참조를위한 몇 가지 링크입니다.
Excellibrary - GNU 더 작은 GPL
epplus - GNU Lesser General Public License (LGPL)
NPOI - 아파치 라이센스

여기서 Excellibrary에 대한 몇 가지 예제 코드 :

다음은 데이터베이스에서 데이터를 가져 와서 통합 문서 작성 예입니다. Excellibrary 코드는 하단의 단일 줄입니다.

//Create the data set and table
DataSet ds = new DataSet("New_DataSet");
DataTable dt = new DataTable("New_DataTable");

//Set the locale for each
ds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
dt.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;

//Open a DB connection (in this example with OleDB)
OleDbConnection con = new OleDbConnection(dbConnectionString);
con.Open();

//Create a query and fill the data table with the data from the DB
string sql = "SELECT Whatever FROM MyDBTable;";
OleDbCommand cmd = new OleDbCommand(sql, con);
OleDbDataAdapter adptr = new OleDbDataAdapter();

adptr.SelectCommand = cmd;
adptr.Fill(dt);
con.Close();

//Add the table to the data set
ds.Tables.Add(dt);

//Here's the easy part. Create the Excel worksheet from the data set
ExcelLibrary.DataSetHelper.CreateWorkbook("MyExcelFile.xls", ds);

Excel 파일을 만드는 것은 쉽습니다. Excel 파일을 수동으로 만들 수 있지만 위의 기능은 실제로 저에게 깊은 인상을주었습니다.

다른 팁

XLSX 형식에 만족하면 내 github 프로젝트를 사용해보십시오. epplus. ExcelPackage의 소스로 시작했지만 오늘날은 완전히 다시 쓰기입니다. 범위, 셀 스타일, 차트, 모양, 그림, 범위, 자동 필터 및 기타 많은 것들을 지원합니다.

성공과 함께 다음과 같은 오픈 소스 프로젝트를 사용했습니다.

  • OOXML 형식 용 ExcelPackage (Office 2007)

  • .xls 형식의 NPOI (Office 2003). NPOI 2.0 (베타)도 XLSX를 지원합니다.

내 블로그 게시물을 살펴보십시오.

C#에서 Excel 스프레드 시트 .xls 및 .xlsx 생성.

Excel 테이블 및 동적 차트가있는 NPOI

그리고 Microsoft Office에 Open XML SDK 2.0을 사용하는 것은 어떻습니까?

몇 가지 이점 :

  • 사무실을 설치할 필요가 없습니다
  • Microsoft = Acent MSDN 문서에 의해 만들어졌습니다
  • 프로젝트에서 사용할 .NET DLL 중 하나만 사용합니다
  • SDK에는 Diff, Validator 등과 같은 많은 도구가 제공됩니다.

연결:

OLEDB를 사용하여 Excel 파일을 만들고 조작 할 수 있습니다. 이것을 확인하십시오 : OLEDB를 사용하여 Excel을 읽고 쓰십시오.

일반적인 예 :

using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\temp\\test.xls;Extended Properties='Excel 8.0;HDR=Yes'"))
{
  conn.Open();
  OleDbCommand cmd = new OleDbCommand("CREATE TABLE [Sheet1] ([Column1] string, [Column2] string)", conn);
  cmd.ExecuteNonQuery();
}

편집 - 더 많은 링크 :

상업용 솔루션, .NET 용 스프레드 시트 기어 할 것입니다.

라이브 ASP.NET (C# 및 VB) 샘플을 볼 수 있습니다. 여기 평가 버전을 다운로드하십시오 여기.

면책 조항 : 스프레드 시트 기어 LLC를 소유하고 있습니다

내가 사용한 몇 가지 옵션 :

XLSX가 필수 인 경우 : ExcelPackage 좋은 출발이지만 개발자가 그 일을 그만두면서 죽었습니다. EXML은 거기에서 픽업하여 몇 가지 기능을 추가했습니다. exml 나쁜 옵션이 아니며, 여전히 몇 개의 프로덕션 웹 사이트에서 사용하고 있습니다.

그래도 모든 새로운 프로젝트에 대해 NPOI, .NET 포트 아파치 포이. NPOI 2.0 (알파) XLSX도 지원합니다.

매우 가벼운 옵션은 HTML 테이블을 사용하는 것일 수 있습니다. 파일에 헤드, 본문 및 테이블 태그를 만들고 .xls 확장자가있는 파일로 저장하십시오. 공식을 포함하여 출력을 스타일링하는 데 사용할 수있는 Microsoft 특정 속성이 있습니다.

웹 응용 프로그램에서 이것을 코딩하지 않을 수도 있지만 여기에 있습니다. 예시 HTML 테이블을 통한 Excel 파일의 구성. 이 기술은 콘솔 앱, 데스크탑 앱 또는 서비스를 코딩하는 경우 사용할 수 있습니다.

당신이 사용할 수있는 ExcelxMlwriter.

잘 작동합니다.

Excel 2007/2010 파일을 작성하는 경우이 오픈 소스 프로젝트를 시도해보십시오. https://github.com/closedxml/closedxml

XML 문서의 번거 로움없이 파일 (VBA와 유사)을 조작하는 객체 지향 방법을 제공합니다. C# 및 Visual Basic (VB)과 같은 모든 .NET 언어에서 사용할 수 있습니다.

ClosedXML을 사용하면 Excel 응용 프로그램없이 Excel 2007/2010 파일을 만들 수 있습니다. 일반적인 예는 웹 서버에서 Excel 보고서를 작성하는 것입니다.

var workbook = new XLWorkbook();
var worksheet = workbook.Worksheets.Add("Sample Sheet");
worksheet.Cell("A1").Value = "Hello World!";
workbook.SaveAs("HelloWorld.xlsx");

실제로 확인하고 싶을 수도 있습니다 인터 로프 클래스. 당신은 OLE이라고 말하지 않지만 (이것은 그렇지 않습니다), Interop 클래스는 사용하기가 매우 쉽습니다.

시도하지 않았다면 감동을받을 수 있습니다.

Microsoft에 대해 경고하십시오 위치 이에:

Microsoft는 현재 불안정한 동작 및///// 구성 요소 (ASP, ASP.NET, DCOM 및 NT 서비스 포함)에서 무인이 아닌 비회적 클라이언트 애플리케이션 또는 구성 요소 (ASP, ASP.NET, DCOM 및 NT 서비스 포함)에서 Microsoft Office 응용 프로그램의 자동화를 권장하지 않으며 지원하지 않습니다. 또는이 환경에서 사무실이 운영 될 때 교착 상태.

여기에 완전 무료 C# 라이브러리가 있습니다. DataSet, DataTable 또는 List<> OpenXML 라이브러리를 사용하여 Genuine Excel 2007 .xlsx 파일로 :

http://mikesknowledgebase.com/pages/csharp/exporttoexcel.htm

전체 소스 코드가 제공됩니다 - 무료 - 지침 및 데모 응용 프로그램과 함께 제공됩니다.

이 클래스를 애플리케이션에 추가 한 후 데이터 세트를 내보내기 위해 한 줄의 코드로 엑셀을 내보낼 수 있습니다.

CreateExcelFile.CreateExcelDocument(myDataSet, "C:\\Sample.xlsx");

그것보다 훨씬 간단하지 않습니다 ...

서버에 Excel이 존재할 필요조차 없습니다.

당신은 그것을 사용하여 파일을 만드는 것을 고려할 수 있습니다 XML 스프레드 시트 2003 체재. 이것은 a를 사용하는 간단한 XML 형식입니다 잘 문서화 된 스키마.

당신은보고 싶을 수도 있습니다 gembox.spreadsheet.

모든 기능을 갖춘 무료 버전이 있지만 시트 당 150 행, 통합 문서 당 5 장으로 제한됩니다.

나는 아직 그것을 직접 사용할 필요가 없었지만 흥미로워 보입니다.

SyncFusion Essential XLSIO 이것을 할 수 있습니다. Microsoft Office에 의존하지 않으며 다른 플랫폼에 대한 특정 지원도 있습니다.

코드 샘플 :

//Creates a new instance for ExcelEngine.
ExcelEngine excelEngine = new ExcelEngine();
//Loads or open an existing workbook through Open method of IWorkbooks
IWorkbook workbook = excelEngine.Excel.Workbooks.Open(fileName);
//To-Do some manipulation|
//To-Do some manipulation
//Set the version of the workbook.
workbook.Version = ExcelVersion.Excel2013;
//Save the workbook in file system as xlsx format
workbook.SaveAs(outputFileName);

전체 컨트롤 제품군은 커뮤니티 라이센스 자격이있는 경우 프로그램 (수익이 백만 달러 미만). 참고 : 나는 syncfusion을 위해 일합니다.

잘,

당신은 또한 타사 라이브러리를 사용할 수도 있습니다 바로.

이 라이브러리는 컴퓨터에 Excel을 설치할 필요가 없다는 이점이 있습니다.

다양한 Office 2003 XML 라이브러리는 소규모 Excel 파일에 잘 작동합니다. 그러나 XML 형식으로 저장된 대규모 통합 문서의 크기가 문제가되는 것을 발견했습니다. 예를 들어, 내가 작업하는 통합 문서는 새로운 (그리고 더 단단히 포장 된) XLSX 형식에서 40MB 일 것입니다.

저의 연구가 저를 데려온 한, 구형 바이너리 파일 형식으로 출력 할 수있는 두 개의 상용 패키지가 있습니다. 그들은:

저렴하지 않습니다 (각각 500USD 및 800USD는 생각합니다). 그러나 둘 다 Excel 자체와 독립적으로 작동합니다.

내가 궁금한 점은 OpenOffice.org와 같은 Excel 출력 모듈입니다. Java에서 .NET으로 포팅 될 수 있는지 궁금합니다.

OpenXML은 서버에 MS Excel을 설치하는 것을 피하는 데 도움이되는 좋은 대안입니다. Microsoft에서 제공하는 Open XML SDK 2.0은 열린 XML 패키지를 조작하는 작업과 패키지 내에서 열린 XML 스키마 요소를 단순화합니다. Open XML Application Programming Interface (API)는 개발자가 열린 XML 패키지에서 수행하는 많은 일반적인 작업을 캡슐화합니다.

이것 좀 봐 OpenXML : 서버에 MS Excel 설치를 피하는 데 도움이되는 대안

나는 XML 스프레드 시트를 생성하는 것에 동의합니다. 다음은 C# 3에 대한 방법에 대한 예입니다 (VB 9 : P의 모든 사람 만 블로그). http://www.aaron-powell.com/linq-to-xml-to-excel

방금 최근에 사용했습니다 flexcel.net 그리고 그것은 훌륭한 도서관이라는 것을 알았습니다! 나는 너무 많은 소프트웨어 제품에 대해 말하지 않습니다. 전체 판매 피치를 여기에 제공 할 필요는 없으며 웹 사이트의 모든 기능을 읽을 수 있습니다.

상업용 제품이지만 구매하면 전체 소스를 얻습니다. 그래서 나는 당신이 정말로 원한다면 당신의 어셈블리에 그것을 컴파일 할 수 있다고 생각합니다. 그렇지 않으면 Xcopy에 대한 추가 어셈블리 일뿐입니다. 구성이나 설치 또는 그와 비슷한 것입니다.

.NET 프레임 워크로서 타사 라이브러리 없이이 작업을 수행 할 수있는 방법을 찾을 수 없다고 생각합니다.

문제를 직접 해결하는 타사 솔루션에 대한 다른 참조를 추가하고 싶을뿐입니다. http://www.officewriter.com

(면책 조항 : 사무실 라이터를 만드는 회사 인 Softartisans에서 일합니다)

System.io.StreamWriter를 사용하여 Excel Object를 사용하지 않고 Excel로 데이터 세트를 내보내는 간단한 코드를 작성했습니다.

아래는 데이터 세트의 모든 테이블을 읽고 하나씩 시트에 작성하는 코드입니다. 나는 도움을 받았다 이 기사.

public static void exportToExcel(DataSet source, string fileName)
{
        const string endExcelXML = "</Workbook>";
        const string startExcelXML = "<xml version>\r\n<Workbook " +
                 "xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"\r\n" +
                 " xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\n " +
                 "xmlns:x=\"urn:schemas-    microsoft-com:office:" +
                 "excel\"\r\n xmlns:ss=\"urn:schemas-microsoft-com:" +
                 "office:spreadsheet\">\r\n <Styles>\r\n " +
                 "<Style ss:ID=\"Default\" ss:Name=\"Normal\">\r\n " +
                 "<Alignment ss:Vertical=\"Bottom\"/>\r\n <Borders/>" +
                 "\r\n <Font/>\r\n <Interior/>\r\n <NumberFormat/>" +
                 "\r\n <Protection/>\r\n </Style>\r\n " +
                 "<Style ss:ID=\"BoldColumn\">\r\n <Font " +
                 "x:Family=\"Swiss\" ss:Bold=\"1\"/>\r\n </Style>\r\n " +
                 "<Style     ss:ID=\"StringLiteral\">\r\n <NumberFormat" +
                 " ss:Format=\"@\"/>\r\n </Style>\r\n <Style " +
                 "ss:ID=\"Decimal\">\r\n <NumberFormat " +
                 "ss:Format=\"0.0000\"/>\r\n </Style>\r\n " +
                 "<Style ss:ID=\"Integer\">\r\n <NumberFormat " +
                 "ss:Format=\"0\"/>\r\n </Style>\r\n <Style " +
                 "ss:ID=\"DateLiteral\">\r\n <NumberFormat " +
                 "ss:Format=\"mm/dd/yyyy;@\"/>\r\n </Style>\r\n " +
                 "</Styles>\r\n ";
        System.IO.StreamWriter excelDoc = null;
        excelDoc = new System.IO.StreamWriter(fileName);

        int sheetCount = 1;
        excelDoc.Write(startExcelXML);
        foreach (DataTable table in source.Tables)
        {
            int rowCount = 0;
            excelDoc.Write("<Worksheet ss:Name=\"" + table.TableName + "\">");
            excelDoc.Write("<Table>");
            excelDoc.Write("<Row>");
            for (int x = 0; x < table.Columns.Count; x++)
            {
                excelDoc.Write("<Cell ss:StyleID=\"BoldColumn\"><Data ss:Type=\"String\">");
                excelDoc.Write(table.Columns[x].ColumnName);
                excelDoc.Write("</Data></Cell>");
            }
            excelDoc.Write("</Row>");
            foreach (DataRow x in table.Rows)
            {
                rowCount++;
                //if the number of rows is > 64000 create a new page to continue output
                if (rowCount == 64000)
                {
                    rowCount = 0;
                    sheetCount++;
                    excelDoc.Write("</Table>");
                    excelDoc.Write(" </Worksheet>");
                    excelDoc.Write("<Worksheet ss:Name=\"" + table.TableName + "\">");
                    excelDoc.Write("<Table>");
                }
                excelDoc.Write("<Row>"); //ID=" + rowCount + "
                for (int y = 0; y < table.Columns.Count; y++)
                {
                    System.Type rowType;
                    rowType = x[y].GetType();
                    switch (rowType.ToString())
                    {
                        case "System.String":
                            string XMLstring = x[y].ToString();
                            XMLstring = XMLstring.Trim();
                            XMLstring = XMLstring.Replace("&", "&");
                            XMLstring = XMLstring.Replace(">", ">");
                            XMLstring = XMLstring.Replace("<", "<");
                            excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
                                           "<Data ss:Type=\"String\">");
                            excelDoc.Write(XMLstring);
                            excelDoc.Write("</Data></Cell>");
                            break;
                        case "System.DateTime":
                            //Excel has a specific Date Format of YYYY-MM-DD followed by  
                            //the letter 'T' then hh:mm:sss.lll Example 2005-01-31T24:01:21.000
                            //The Following Code puts the date stored in XMLDate 
                            //to the format above
                            DateTime XMLDate = (DateTime)x[y];
                            string XMLDatetoString = ""; //Excel Converted Date
                            XMLDatetoString = XMLDate.Year.ToString() +
                                 "-" +
                                 (XMLDate.Month < 10 ? "0" +
                                 XMLDate.Month.ToString() : XMLDate.Month.ToString()) +
                                 "-" +
                                 (XMLDate.Day < 10 ? "0" +
                                 XMLDate.Day.ToString() : XMLDate.Day.ToString()) +
                                 "T" +
                                 (XMLDate.Hour < 10 ? "0" +
                                 XMLDate.Hour.ToString() : XMLDate.Hour.ToString()) +
                                 ":" +
                                 (XMLDate.Minute < 10 ? "0" +
                                 XMLDate.Minute.ToString() : XMLDate.Minute.ToString()) +
                                 ":" +
                                 (XMLDate.Second < 10 ? "0" +
                                 XMLDate.Second.ToString() : XMLDate.Second.ToString()) +
                                 ".000";
                            excelDoc.Write("<Cell ss:StyleID=\"DateLiteral\">" +
                                         "<Data ss:Type=\"DateTime\">");
                            excelDoc.Write(XMLDatetoString);
                            excelDoc.Write("</Data></Cell>");
                            break;
                        case "System.Boolean":
                            excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
                                        "<Data ss:Type=\"String\">");
                            excelDoc.Write(x[y].ToString());
                            excelDoc.Write("</Data></Cell>");
                            break;
                        case "System.Int16":
                        case "System.Int32":
                        case "System.Int64":
                        case "System.Byte":
                            excelDoc.Write("<Cell ss:StyleID=\"Integer\">" +
                                    "<Data ss:Type=\"Number\">");
                            excelDoc.Write(x[y].ToString());
                            excelDoc.Write("</Data></Cell>");
                            break;
                        case "System.Decimal":
                        case "System.Double":
                            excelDoc.Write("<Cell ss:StyleID=\"Decimal\">" +
                                  "<Data ss:Type=\"Number\">");
                            excelDoc.Write(x[y].ToString());
                            excelDoc.Write("</Data></Cell>");
                            break;
                        case "System.DBNull":
                            excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
                                  "<Data ss:Type=\"String\">");
                            excelDoc.Write("");
                            excelDoc.Write("</Data></Cell>");
                            break;
                        default:
                            throw (new Exception(rowType.ToString() + " not handled."));
                    }
                }
                excelDoc.Write("</Row>");
            }
            excelDoc.Write("</Table>");
            excelDoc.Write(" </Worksheet>");
            sheetCount++;
        }


        excelDoc.Write(endExcelXML);
        excelDoc.Close();
    }

IKVM + 포이

또는, 당신은 인터 로프를 사용할 수 있습니다 ...

다음은 LINQ에서 XML로 수행하는 방법입니다. 샘플 코드로 구성됩니다.

LINQ로 Excel 데이터를 빠르게 가져오고 내보내기

네임 스페이스 등을 가져와야하므로 외부 종속성을 피할 수 있기 때문에 조금 복잡합니다.

(물론 C#이 아닌 VB .NET이지만 자체 프로젝트에서 VB .NET 항목을 XML 리터럴을 사용하고 C#에서 다른 모든 것을 수행 할 수 있습니다.)

Infragistics 또는 SyncFusion과 같은 일부 타사 구성 요소 공급 업체는 Microsoft Excel을 설치할 필요가없는 매우 우수한 Excel 내보내기 기능을 제공합니다.

이 공급 업체는 고급 UI 그리드 구성 요소를 제공하기 때문에 애플리케이션의 사용자 인터페이스에서 그리드의 현재 상태를 모방하기 위해 Excel 내보내기 스타일과 레이아웃을 원할 경우 이러한 구성 요소는 특히 편리합니다.

내보내기가 내보낼 데이터에 중점을두고 UI에 대한 링크가없는 서버 측에서 내보내기가 실행되도록 의도 된 경우, 나는 무료 오픈 소스 옵션 중 하나 (예 : Excellibrary)로 이동합니다.

이전에 Microsoft Office Suite에서 서버 측 자동화를 사용하려는 프로젝트에 참여했습니다. 이 경험을 바탕으로 나는 그 접근법을 강력히 추천 할 것입니다.

public class GridViewExportUtil
{
    public static void Export(string fileName, GridView gv)
    {
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.AddHeader(
            "content-disposition", string.Format("attachment; filename={0}", fileName));
        HttpContext.Current.Response.ContentType = "application/ms-excel";

        using (StringWriter sw = new StringWriter())
        {
            using (HtmlTextWriter htw = new HtmlTextWriter(sw))
            {
                //  Create a form to contain the grid
                Table table = new Table();

                //  add the header row to the table
                if (gv.HeaderRow != null)
                {
                    GridViewExportUtil.PrepareControlForExport(gv.HeaderRow);
                    table.Rows.Add(gv.HeaderRow);
                }

                //  add each of the data rows to the table
                foreach (GridViewRow row in gv.Rows)
                {
                    GridViewExportUtil.PrepareControlForExport(row);
                    table.Rows.Add(row);
                }

                //  add the footer row to the table
                if (gv.FooterRow != null)
                {
                    GridViewExportUtil.PrepareControlForExport(gv.FooterRow);
                    table.Rows.Add(gv.FooterRow);
                }

                //  render the table into the htmlwriter
                table.RenderControl(htw);

                //  render the htmlwriter into the response
                HttpContext.Current.Response.Write(sw.ToString());
                HttpContext.Current.Response.End();
            }
        }
    }

    /// <summary>
    /// Replace any of the contained controls with literals
    /// </summary>
    /// <param name="control"></param>
    private static void PrepareControlForExport(Control control)
    {
        for (int i = 0; i < control.Controls.Count; i++)
        {
            Control current = control.Controls[i];
            if (current is LinkButton)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
            }
            else if (current is ImageButton)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
            }
            else if (current is HyperLink)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
            }
            else if (current is DropDownList)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
            }
            else if (current is CheckBox)
            {
                control.Controls.Remove(current);
                control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
            }

            if (current.HasControls())
            {
                GridViewExportUtil.PrepareControlForExport(current);
            }
        }
    }
}

안녕하세요이 솔루션은 그리드보기를 Excel 파일로 내보내는 것입니다.

이 라이브러리를 사용하여 멋지게 형식화 된 Excel 파일을 만들 수 있습니다.http://officehelper.codeplex.com/documentation
아래 샘플 참조 :

using (ExcelHelper helper = new ExcelHelper(TEMPLATE_FILE_NAME, GENERATED_FILE_NAME))
{
    helper.Direction = ExcelHelper.DirectionType.TOP_TO_DOWN;
    helper.CurrentSheetName = "Sheet1";
    helper.CurrentPosition = new CellRef("C3");

    //the template xlsx should contains the named range "header"; use the command "insert"/"name".
    helper.InsertRange("header");

    //the template xlsx should contains the named range "sample1";
    //inside this range you should have cells with these values:
    //<name> , <value> and <comment>, which will be replaced by the values from the getSample()
    CellRangeTemplate sample1 = helper.CreateCellRangeTemplate("sample1", new List<string> {"name", "value", "comment"}); 
    helper.InsertRange(sample1, getSample());

    //you could use here other named ranges to insert new cells and call InsertRange as many times you want, 
    //it will be copied one after another;
    //even you can change direction or the current cell/sheet before you insert

    //typically you put all your "template ranges" (the names) on the same sheet and then you just delete it
    helper.DeleteSheet("Sheet3");
}        

샘플처럼 보이는 곳 :

private IEnumerable<List<object>> getSample()
{
    var random = new Random();

    for (int loop = 0; loop < 3000; loop++)
    {
        yield return new List<object> {"test", DateTime.Now.AddDays(random.NextDouble()*100 - 50), loop};
    }
}

The simplest and fastest way to create an Excel file from C# is to use the Open XML Productivity Tool. The Open XML Productivity Tool comes with the Open XML SDK installation. The tool reverse engineers any Excel file into C# code. The C# code can then be used to re-generate that file.

An overview of the process involved is:

  1. Install the Open XML SDK with the tool.
  2. Create an Excel file using the latest Excel client with desired look. Name it DesiredLook.xlsx.
  3. With the tool open DesiredLook.xlsx and click the Reflect Code button near the top. enter image description here
  4. The C# code for your file will be generated in the right pane of the tool. Add this to your C# solution and generate files with that desired look.

As a bonus, this method works for any Word and PowerPoint files. As the C# developer, you will then make changes to the code to fit your needs.

I have developed a simple WPF app on github which will run on Windows for this purpose. There is a placeholder class called GeneratedClass where you can paste the generated code. If you go back one version of the file, it will generate an excel file like this:

enter image description here

Some useful Excel automation in C# , u can find from the following link.

http://csharp.net-informations.com/excel/csharp-excel-tutorial.htm

bolton.

Look at samples how to create Excel files.

There are examples in C# and VB.NET

It manages XSL XSLX and CSV Excel files.

http://www.devtriogroup.com/ExcelJetcell/Samples

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top