使用C#格式化现有Excel文件表

时间:2015-06-23 16:55:38

标签: c# excel

我在xslx文件中收到一些报告,该文件有2张,数据很好,但文件没有格式化。我发现的大多数帖子都谈到了在创建文件时格式化文件,但我想知道是否有一种方法可以在接收到c#代码后使用c#代码处理文件(例如:适合列到内容)? 谢谢。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ClosedXML;
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.CSharp;
using DocumentFormat.OpenXml.Office.Excel;

namespace ExcelFormatter
{
    class MainScript
    {
        public static void Main(string[] args)
        {
            string file = args[0];

            Excel.Application xlApp;
            Excel.Workbook xlWorkBook;
            Excel.Worksheet xlWorkSheet;

            object misValue = System.Reflection.Missing.Value;
            Excel.Range chartRange;

            xlApp = new Excel.Application();
            xlWorkBook = xlApp.Workbooks.Add(file);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

            chartRange = xlWorkSheet.get_Range("A1", "F1");
            chartRange.Cells.Font.Bold = true;

            xlWorkBook.Save();
            xlWorkBook.Close(true, file, misValue);
            xlApp.Quit();
        }
    }
}

2 个答案:

答案 0 :(得分:0)

我使用ClosedXML来操作使用OpenXML标准创建的Excel文件。它发现它易于使用,并允许我对我的文档做很多事情。希望这会有所帮助。

瓦德

以下是我所做的一个例子。它在VB.Net中,但您应该能够毫无问题地进行转换。

'Open the workbook and then open the worksheet I want to work with.
Dim workbook = New XLWorkbook("<filepath>")
Dim worksheet = workbook.Worksheet("<worksheetname>")

' Throw an exception if there is no sheet.
If worksheet Is Nothing Then
    Throw New ArgumentException("Sheet is missing")
End If

'Set number formatting.  You can look at the closedxml documentation to see what the number should be
worksheet.Cell("G5").Style.NumberFormat.SetNumberFormatId(1)

'Merge and style a group of cells
Dim cellRange = "A1:A12"
worksheet.Range(cellRange).Merge.Value = colName
worksheet.Range(cellRange).Style.Fill.BackgroundColor = XLColor.Black
worksheet.Range(cellRange).Style.Font.FontColor = XLColor.White
worksheet.Range(cellRange).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center

'Auto adjust the column widths      
worksheet.Columns.AdjustToContents()

workbook.SaveAs("<filename>")

答案 1 :(得分:0)

您可以使用EasyXLS导入xlsx文件,然后应用您需要的格式:

// Create an instance of the class that imports XLSX files
ExcelDocument workbook = new ExcelDocument();

// Import XLSX file
workbook.easy_LoadXLSXFile(filePath);

// Get the table of data from the first sheet
ExcelTable xlsTable = ((ExcelWorksheet)workbook.easy_getSheetAt(0)).easy_getExcelTable();

// Create the formatting style for cells
ExcelStyle xlsStyle = new ExcelStyle();
xlsStyle.setHorizontalAlignment(Alignment.ALIGNMENT_LEFT);
xlsStyle.setForeground(Color.DarkGray);

//Apply the formatting to A1 cell
xlsTable.easy_getCell(0, 0).setStyle(xlsStyle);

// Resave the XLSX file
workbook.easy_WriteXLSXFile(newFormattedFilePath);

查看formatting Excel cells上的此链接,了解更多具体细节。