使用c#检索excel文件中的单元格格式

本文关键字:单元格 格式 文件 检索 excel 使用 | 更新日期: 2023-09-27 18:03:14

是否有任何解决方案在检索单元格格式,如单元格颜色,字体样式,边框,线条和单元格大小,并使用c#将其保存为xml文件?

我已经有代码来获得单元格值,并在xml转换,但我没有得到每个单元格的格式。谢谢你。

public class ConvertExcelToXml
{
    /// <summary>
    ///  Read Data from selected excel file into DataTable
    /// </summary>
    /// <param name="filename">Excel File Path</param>
    /// <returns></returns>
    private DataTable ReadExcelFile(string filename)
    {
        // Initialize an instance of DataTable
        DataTable dt = new DataTable();
        try
        {
            // Use SpreadSheetDocument class of Open XML SDK to open excel file
            using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(filename, false))
            {
                // Get Workbook Part of Spread Sheet Document
                WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;
                // Get all sheets in spread sheet document 
                IEnumerable<Sheet> sheetcollection = spreadsheetDocument.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>();
                // Get relationship Id
                string relationshipId = sheetcollection.First().Id.Value;
                // Get sheet1 Part of Spread Sheet Document
                WorksheetPart worksheetPart = (WorksheetPart)spreadsheetDocument.WorkbookPart.GetPartById(relationshipId);
                // Get Data in Excel file
                SheetData sheetData = worksheetPart.Worksheet.Elements<SheetData>().First();
                IEnumerable<Row> rowcollection = sheetData.Descendants<Row>();
                if (rowcollection.Count() == 0)
                {
                    return dt;
                }
                // Add columns
                foreach (Cell cell in rowcollection.ElementAt(0))
                {
                    dt.Columns.Add(GetValueOfCell(spreadsheetDocument, cell));
                }
                // Add rows into DataTable
                foreach (Row row in rowcollection)
                {
                    DataRow temprow = dt.NewRow();
                    int columnIndex = 0;
                    foreach (Cell cell in row.Descendants<Cell>())
                    {
                        // Get Cell Column Index
                        int cellColumnIndex = GetColumnIndex(GetColumnName(cell.CellReference));
                        if (columnIndex < cellColumnIndex)
                        {
                            do
                            {
                                temprow[columnIndex] = string.Empty;
                                columnIndex++;
                            }
                            while (columnIndex < cellColumnIndex);
                        }
                        temprow[columnIndex] = GetValueOfCell(spreadsheetDocument, cell);
                        columnIndex++;
                    }
                    // Add the row to DataTable
                    // the rows include header row
                    dt.Rows.Add(temprow);
                }
            }
            // Here remove header row
            dt.Rows.RemoveAt(0);
            return dt;
        }
        catch (IOException ex)
        {
            throw new IOException(ex.Message);
        }
    }
    /// <summary>
    ///  Get Value of Cell 
    /// </summary>
    /// <param name="spreadsheetdocument">SpreadSheet Document Object</param>
    /// <param name="cell">Cell Object</param>
    /// <returns>The Value in Cell</returns>
    private static string GetValueOfCell(SpreadsheetDocument spreadsheetdocument, Cell cell)
    {
        // Get value in Cell
        SharedStringTablePart sharedString = spreadsheetdocument.WorkbookPart.SharedStringTablePart;
        if (cell.CellValue == null)
        {
            return string.Empty;
        }
        string cellValue = cell.CellValue.InnerText;
        // The condition that the Cell DataType is SharedString
        if (cell.DataType != null && cell.DataType.Value == CellValues.SharedString)
        {
            return sharedString.SharedStringTable.ChildElements[int.Parse(cellValue)].InnerText;
        }
        else
        {
            return cellValue;
        }
    }
    /// <summary>
    /// Get Column Name From given cell name
    /// </summary>
    /// <param name="cellReference">Cell Name(For example,A1)</param>
    /// <returns>Column Name(For example, A)</returns>
    private string GetColumnName(string cellReference)
    {
        // Create a regular expression to match the column name of cell
        Regex regex = new Regex("[A-Za-z]+");
        Match match = regex.Match(cellReference);
        return match.Value;
    }
    /// <summary>
    /// Get Index of Column from given column name
    /// </summary>
    /// <param name="columnName">Column Name(For Example,A or AA)</param>
    /// <returns>Column Index</returns>
    private int GetColumnIndex(string columnName)
    {
        int columnIndex = 0;
        int factor = 1;
        // From right to left
        for (int position = columnName.Length - 1; position >= 0; position--)   
        {
            // For letters
            if (Char.IsLetter(columnName[position]))
            {
                columnIndex += factor * ((columnName[position] - 'A') + 1) - 1;
                factor *= 26;
            }
        }
        return columnIndex;
    }
    /// <summary>
    /// Convert DataTable to Xml format
    /// </summary>
    /// <param name="filename">Excel File Path</param>
    /// <returns>Xml format string</returns>
    public string GetXML(string filename)
    {
        using (DataSet ds = new DataSet())
        {
            ds.Tables.Add(this.ReadExcelFile(filename));
            return ds.GetXml();
        }
    }
}

使用c#检索excel文件中的单元格格式

如果您使用Microsoft.Office.Interop.Excel.Range表示您的单元格,并且您有它的rowNumbercolumnNumber

颜色使用:

int colorNumber = System.Convert.ToInt32(((Range) worksheet.Cells[rowNumber,columnNumber]).Interior.Color);
Color color = System.Drawing.ColorTranslator.FromOle(colorNumber);

font style (FontName,FontSize):

string FontName = ((Range) worksheet.Cells[rowNumber,columnNumber]).Style.Font.Name
int FontSize = System.Convert.ToInt32(((Range) worksheet.Cells[rowNumber,columnNumber]).Style.Font.Size);
边境(大小、风格):

int size = System.Convert.ToInt32(((Range) worksheet.Cells[rowNumber,columnNumber]).Borders.Weight);  
Excel.XlLineStyle style = ((Range) worksheet.Cells[rowNumber,columnNumber]).Borders.LineStyle;
列宽/高

:

int width = System.Convert.ToInt32(((Range) worksheet.Cells[rowNumber,columnNumber]).EntireColumn.ColumnWidth);
int height= System.Convert.ToInt32(((Range) worksheet.Cells[rowNumber,columnNumber]).EntireColumn.ColumnHeight);