使用C#将Excel单元格值从数字转换为文本

时间:2015-03-17 07:19:10

标签: c# asp.net excel openxml

我正在使用以下流程打开我的Excel:

if (dt != null) 
{
    foreach(DataColumn dc in dt.Columns) 
    {
        Response.Write(dc.ColumnName + "\t");
        //sep = ";";
    }
    Response.Write(System.Environment.NewLine);
    foreach(DataRow dr in dt.Rows) 
    {
        for (int i = 0; i < dt.Columns.Count; i++) 
        {
            Response.Write(dr[i].ToString() + "\t");
        }
        Response.Write("\n");
    }

    Response.Flush();
    Response.SuppressContent = true;
    HttpContext.Current.ApplicationInstance.CompleteRequest();
}

在我的数据表中,我有一个数值,当excel渲染时,它与右边对齐,因为这是excel的默认属性,可以正确对齐数值。但根据我的要求,我必须将该数值与excel中的左侧对齐。为此,我尝试从后端添加空格,但excel在渲染时忽略空间。我尝试在列值之前添加'但是当excel呈现时,列值显示为'2015'2016

任何人都可以帮我解决这个问题。提前谢谢。

1 个答案:

答案 0 :(得分:0)

您要导出为CSV文件。如果您使用OpenXML,您将能够指定列数据类型(格式)并将左对齐应用于数字,例如:

using OfficeOpenXml;
using OfficeOpenXml.Style;

public static bool IsNumeric(this DataColumn col) {
    if (col == null)
        return false;

    //This should be moved to const in order to improve performance
    var numericTypes = new [] { typeof(Byte), typeof(Decimal), typeof(Double), typeof(Int16), typeof(Int32), typeof(Int64), typeof(SByte), typeof(Single), typeof(UInt16), typeof(UInt32), typeof(UInt64)};
    return numericTypes.Contains(col.DataType);
}

public static void ExportToExcelOpen(DataSet ds, string filename)
{
    // Create a spreadsheet document by supplying the filename
    // By default, AutoSave = true, Editable = true, and Type = xlsx

    HttpContext.Current.Response.ClearHeaders();
    HttpContext.Current.Response.ClearContent();
    HttpContext.Current.Response.Clear();
    HttpContext.Current.Response.Buffer = true;
    HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + filename);
    HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    HttpContext.Current.Response.Charset = "";

    MemoryStream ms = new MemoryStream();

    using (var objSpreadsheet = SpreadsheetDocument.Create(ms, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
    {
        var workbookPart = objSpreadsheet.AddWorkbookPart();
        objSpreadsheet.WorkbookPart.Workbook = new DocumentFormat.OpenXml.Spreadsheet.Workbook();
        objSpreadsheet.WorkbookPart.Workbook.Sheets = new DocumentFormat.OpenXml.Spreadsheet.Sheets();

        uint sheetId = 1;

        foreach (DataTable table in ds.Tables)
        {
            var sheetPart = objSpreadsheet.WorkbookPart.AddNewPart<WorksheetPart>();
            var sheetData = new DocumentFormat.OpenXml.Spreadsheet.SheetData();
            sheetPart.Worksheet = new DocumentFormat.OpenXml.Spreadsheet.Worksheet(sheetData);

            DocumentFormat.OpenXml.Spreadsheet.Sheets sheets = objSpreadsheet.WorkbookPart.Workbook.GetFirstChild<DocumentFormat.OpenXml.Spreadsheet.Sheets>();
            string relationshipId = objSpreadsheet.WorkbookPart.GetIdOfPart(sheetPart);

            sheetId += 1;

            DocumentFormat.OpenXml.Spreadsheet.Sheet sheet = new DocumentFormat.OpenXml.Spreadsheet.Sheet() { Id = relationshipId, SheetId = sheetId, Name = table.TableName };
            sheets.Append(sheet);

            DocumentFormat.OpenXml.Spreadsheet.Row headerRow = new DocumentFormat.OpenXml.Spreadsheet.Row();

            Dictionary<string, bool> columns = new Dictionary<string, bool>(); 
            foreach (DataColumn column in table.Columns) 
            { 
                //Check for numeric column HERE!!
                columns.Add(column.ColumnName, column.IsNumeric());   

                DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell(); 
                cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String; 
                cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(column.ColumnName); 
                headerRow.AppendChild(cell); 
            }

            sheetData.AppendChild(headerRow);

            NumberFormatInfo valueNumberFormatInfo = new NumberFormatInfo() { NumberDecimalSeparator = ".", NumberGroupSeparator = String.Empty };
            foreach (DataRow dsrow in table.Rows) 
            { 
                DocumentFormat.OpenXml.Spreadsheet.Row newRow = new DocumentFormat.OpenXml.Spreadsheet.Row(); 
                foreach (KeyValuePair<string, bool> col in columns) 
                { 
                    DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
                    if (col.Value)
                    {
                        cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.Number; 
                        cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(String.Format(valueNumberFormatInfo, "0.####################", dsrow[col.Key]));
                         //Left Alignment HERE
                         cell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Left;
                    }
                    else
                    {
                        cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String; 
                        cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(dsrow[col.Key].ToString());
                    } 
                    newRow.AppendChild(cell); 
                } 

                sheetData.AppendChild(newRow); 
            }
        }

        objSpreadsheet.Close();
        ms.WriteTo(HttpContext.Current.Response.OutputStream);
        ms.Close();

        HttpContext.Current.Response.Flush();
        HttpContext.Current.Response.End();
    }
}

参考:http://forums.asp.net/t/1860267.aspx?How+to+retain+data+types+when+exporting+to+Excel+using+Open+XML

参考:Set text align to center in an Excel document using OpenXML with C#