0

I am using the below process to open my 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();
}

In my datatable I have one numeric value which align to right when excel renders as this is the default property of excel to align numeric values right. But as per my requirement I have to align that numeric value to the left side in excel. For this I tried adding the space from the back-end but excel ignore space when renders. I tried adding ' before the column value but when excel renders the column value shows like '2015, '2016.

Anybody can help me to figure this out. Thanks in advance.

Jeremy Thompson
  • 61,933
  • 36
  • 195
  • 321
Garvit Gupta
  • 189
  • 1
  • 5
  • 15
  • How are you going? Is this resolved or did you need anymore help? – Jeremy Thompson Mar 18 '15 at 08:00
  • Thanks for your concern I tried the above code and facing 2 issues: First I am unable to get the reference of "OfficeOpenXml" library, even I have included DocumentFormat.OpenXml to my peoject. Second you have used a function "IsNumeric" in line "columns.Add(column.ColumnName, column.IsNumeric());" Here it is giving me error "System.Data.DataColumn" does not contain a definition of IsNumeric(). Hoping of your reply. – Garvit Gupta Mar 18 '15 at 17:50
  • Ok..For my first issue I have added "Install-Package EPPlus" but second is still not resolved. I am also facing issue in line "cell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Left;" says "DocumentFormat.OpenXml.Spreadsheet" does not contain a definition for "Style". Still working If I will get any resolution I update. – Garvit Gupta Mar 18 '15 at 18:09
  • Use .net 4 for the extension method and install the [.net office SDK](https://msdn.microsoft.com/en-us/library/office/bb448854.aspx) – Jeremy Thompson Mar 18 '15 at 19:29
  • I am still not able to resolve the issue which I had mentioned in my previous comment. I am getting the issue on line "//cell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Left;" on style. I have also reference to WindiowBase.dll but stil issue is not resolved. In case of string it is working fine but in case of number or decimal I am getting "0.####################" in excel. Can you please give me some solution for this. I have almost completed this. – Garvit Gupta Mar 20 '15 at 18:05
  • Type *cell.Style.HorizontalAlignment =* then press Ctrl + Space to bring up intellisense and choose LeftAlighment – Jeremy Thompson Mar 21 '15 at 02:04
  • But I am not able to find the definition of "Style". I type cell and after type "." the intellisense gets nothing like Style. – Garvit Gupta Mar 21 '15 at 05:20
  • So you got rid of the Extension Method compilation problem by targeting .Net 4.0. And you have downloaded and installed the .Net Office SDK? – Jeremy Thompson Mar 21 '15 at 09:32
  • Yes I get rid of Extension Method compilation by just add the reference of Window.Base.dll but for this I don't need to install .Net Office SDK. – Garvit Gupta Mar 21 '15 at 12:37
  • Cool so you got it working? – Jeremy Thompson Mar 21 '15 at 12:43
  • I am little confused here. In my previous comment I have mentioned 2 issues 1- I am unable to find the definition of IsNumeric(). 2- I am unable to find the definition of "Style" in line "cell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Left". My first issue have resolved when I add the reference of WindiowBase.dll as suggested by you, BUT still my SECOND issue is not resolved that is related to the definition of "Style". – Garvit Gupta Mar 21 '15 at 17:28
  • Finally its working..But I have to comment two lines of code to make it work. 1- "cell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Left" 2- "cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(String.Format(valueNumberFormatInfo, "0.####################", dsrow[col.Key]));". Now my excel is generating the colums as per the column datatypes that I have set in database. Thanks for your support – Garvit Gupta Mar 22 '15 at 12:37

1 Answers1

0

You're exporting as a CSV file. If you use OpenXML you will be able to specify Column DataTypes (formats) and also apply Left Alignment to numbers eg:

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

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

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

Community
  • 1
  • 1
Jeremy Thompson
  • 61,933
  • 36
  • 195
  • 321