Auto fit columns in excel using open xml

I have generate excel using open xml and it contain auto fit property for columns. my problem is that the excel is opening very well in kingsoft spreadsheets
and other tools, but not opening in microsoft excel 2013 and older version. Is there any solution for auto fit columns in excel using open xml and should open in Microsoft excel  all version

Hi Raj12345,
>> I have generate excel using open xml and it contain auto fit property for columns. my problem is that the excel is opening very well in kingsoft spreadsheets and other tools, but not opening in microsoft excel 2013 and older version
I assume you was using OpenXML SDK and I'm afraid we are not able to find the root cause according to your description, would you mind sharing us some code sample to reproduce this issue.
>> Is there any solution for auto fit columns in excel using open xml and should open in Microsoft excel  all version
As far as I know, there is no auto fit property for columns in excel with openxml. I am afraid that you need to calculate the column width depending on the cell contents, and then set the column width. The link below shows more details:
# Solution: How to AutoFit Excel Content
https://social.msdn.microsoft.com/Forums/office/en-US/28aae308-55cb-479f-9b58-d1797ed46a73/solution-how-to-autofit-excel-content?forum=oxmlsdk
Best Regards,
Edward
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click HERE to participate the survey.

Similar Messages

  • Render HTML inside Excel, using Open XML

    Hello guys,
    I am creating excel file using, Open XML.
    The data will be coming from database, and can contain HTML tags.
    e.g. <b>some sample <i style='color:red'> text </i></b>
    I want the HTML to be rendered inside excel sheet, so that user can view well formatted excel..
    Please, Help me out

    Hi J_Prasanna,
    I'm afraid that it's not possible with OpenXML SDK, but it's possible if you use Excel PIA along with Internet Explorer. Use the Internet Explorer COM object to render the HTML content, then copy the document, use the Paste method of the Worksheet object
    to paste the text with format.
    Dim IE As Object
    Set IE = CreateObject("InternetExplorer.Application")
    With IE
    .Visible = False
    .Navigate "about:blank"
    .document.body.InnerHTML = Sheets("Sheet1").Range("A1").Value
    .document.body.createtextrange.execCommand "Copy"
    ActiveSheet.Paste Destination:=Sheets("Sheet1").Range("A1")
    .Quit
    End With
    The code is similar if you use managed project.
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • When reading the Rich Text present in Excel column using open XML its taking it as plain text

    Hello All,
    When i am reading excel columns using open Xml in C# everything is working fine except the column that
    contain Rich Text (ex: bold, italic,color,size). Its reading the Rich Text content as plain text. As we know for Rich Text in open XML we get the text as Runs (C#
    object) which contains the text as value and rpr as run properties. I have also written the code to convert Runs to html. But the issue is that for some Rich Text format its reading it as Runs but most of the Rich Text its reading it as plain text.
    The issue i am getting is, for some rich text its creating RUN and for some of the rich text its not creatingRUN.
    Let me give the example for more understanding:
    Suppose i have two cells in excel which contains the below text.
    1. Rich Text
    1
    2. RichText
    2
    Now when i read these cells using the below code
    var stringTable =spreadsheetDocument.WorkbookPart.GetPartsOfType<SharedStringTablePart>().FirstOrDefault();
    if (stringTable.SharedStringTable.ElementAt(index1).ChildElements.GetItem(0).GetType().Name == "Run")
    Custom code to convert Rich text to HTML...
    else
    Read the plain text...
    Though both the cell contains rich text, one is going in RUN block and one is going in Plain text bloc.
    Also, one thing that i have noticed is when i use standard color for text its consider it as RUNS and when i use color apart from the standard color it does not consider it as RUNS. Same behavior occurs for different combination of text viz. bold, italic, underline
    etc

    Hi Ejaz,
    This forum is for software developers who are using the Open Specification documentation to assist them in developing systems, services, and applications that are interoperable with Microsoft products. The Open Specifications can be found at:
    http://msdn.microsoft.com/en-us/library/cc203350(PROT.10).aspx. Since your post does not appear to be related to the Open Specification documentation set, we would appreciate it if
    you could try to post your question in a more relevant forum. Thank you.
    Open XML Format SDK
    https://social.msdn.microsoft.com/Forums/en-US/home?forum=oxmlsdk&filter=alltypes&sort=lastpostdesc
    Josh Curry (jcurry) | Escalation Engineer | Open Specifications Support Team

  • Change Excel sheet tab color using Open XML dll

    Hi,
    I want to change the sheet tab color of an excel Xlsx  document. I am using the following code but it does not set the sheet color. I get object reference exception when I set the sheet tab color.
    public static string filepath = @"C:\Test\Book1.xlsx";
    private static void ChangeSheetcolor()
    try
    using (SpreadsheetDocument spreadSheetDocument = SpreadsheetDocument.Open(filepath, false))
    WorkbookPart workbookPart = spreadSheetDocument.WorkbookPart;
    IEnumerable<Sheet> sheets = spreadSheetDocument.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>();
    //my code
    WorksheetPart worksheetPart =
    GetWorksheetPartByName(spreadSheetDocument, "Sheet1");
    if (worksheetPart != null)
    // worksheetPart.Worksheet.SheetProperties.TabColor.Rgb = DocumentFormat.OpenXml.HexBinaryValue.FromString("Red");
    worksheetPart.Worksheet.SheetProperties.TabColor.Rgb = DocumentFormat.OpenXml.HexBinaryValue.FromString("#CCCCCC");
    // Save the worksheet.
    worksheetPart.Worksheet.Save();
    catch (Exception ex)
    private static WorksheetPart
    GetWorksheetPartByName(SpreadsheetDocument document,
    string sheetName)
    IEnumerable<Sheet> sheets =
    document.WorkbookPart.Workbook.GetFirstChild<Sheets>().
    Elements<Sheet>().Where(s => s.Name == sheetName);
    if (sheets.Count() == 0)
    //does not exist
    return null;
    string relationshipId = sheets.First().Id.Value;
    WorksheetPart worksheetPart = (WorksheetPart)
    document.WorkbookPart.GetPartById(relationshipId);
    return worksheetPart;
    How to change the sheet tab color using Open XML dlls.
    Thanks
    Ashok

    Hi J_Prasanna,
    I'm afraid that it's not possible with OpenXML SDK, but it's possible if you use Excel PIA along with Internet Explorer. Use the Internet Explorer COM object to render the HTML content, then copy the document, use the Paste method of the Worksheet object
    to paste the text with format.
    Dim IE As Object
    Set IE = CreateObject("InternetExplorer.Application")
    With IE
    .Visible = False
    .Navigate "about:blank"
    .document.body.InnerHTML = Sheets("Sheet1").Range("A1").Value
    .document.body.createtextrange.execCommand "Copy"
    ActiveSheet.Paste Destination:=Sheets("Sheet1").Range("A1")
    .Quit
    End With
    The code is similar if you use managed project.
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • How to auto fit column width?

    Hi experts,
      When I design a input schedule, I find a problem, some columns can auto fit column width when I input numerics, some columns can not! how can I fix my input schedule and let all column can auto fit column width?
    best regard
    Evans.

    Evans,
          If you are using standard template and which is not working for 2 data ranges.
          I think you can customize using VBA Macros. It is possible using Macros. I'm not sure is it BUG from SAP.
         Try to put VBA code in AFTER_REFRESH i guess.
          You can VBA Macro code mention below.
          for Column D: Columns("D:D").EntireColumn.AutoFit
          For all Columns: Cells.EntireColumn.AutoFit
          For Only Data Ranges: Determine columns from data range using VBA code and use VBA code given for Column .
    Thanks,
    Ben.

  • Auto fit column width for subtotals

    Hello,
    We created subtotals using member sorting & grouping in EPM report. some reason Auto fit column width is not working for sub totals.
    Any idea or any one encounter similar issue?
    Thanks,
    Srinivas Thota

    Hi Raju,
    I checked notes but i dont see any details in SP16 patch 01 documentation.
    The note 1683111 related to SP07.
    Thanks,
    Srinivas Thota

  • Unable to capture the adf table column sort icons using open script tool

    Hi All,
    I am new to OATS and I am trying to create script for testing ADF application using open script tool. I face issues in recording two events.
    1. I am unable to record the event of clicking adf table column sort icons that exist on the column header. I tried to use the capture tool, but that couldn't help me.
    2. The second issue is I am unable to capture the panel header text. The component can be identified but I was not able to identify the supporting attribute for the header text.

    Hi keerthi,
    1. I have pasted the code for the first issue
    web
                             .button(
                                       122,
                                       "/web:window[@index='0' or @title='Manage Network Targets - Oracle Communications Order and Service Management - Order and Service Management']/web:document[@index='0' or @name='1824fhkchs_6']/web:form[@id='pt1:_UISform1' or @name='pt1:_UISform1' or @index='0']/web:button[@id='pt1:MA:0:n1:1:pt1:qryId1::search' or @value='Search' or @index='3']")
                             .click();
                        adf
                        .table(
                                  "/web:window[@index='0' or @title='Manage Network Targets - Oracle Communications Order and Service Management - Order and Service Management']/web:document[@index='0' or @name='1c9nk1ryzv_6']/web:ADFTable[@absoluteLocator='pt1:MA:n1:pt1:pnlcltn:resId1']")
                        .columnSort("Ascending", "Name" );
         }

  • How Auto Fit column in DataGrid

    Is it possible to set autofit in DataGrid column ?
    Without auto fit the users must resize the table every
    time.

    Please Check this example
    http://www.flex4ex.com/?p=24

  • Group columns in Excel using XSLT simple transformation

    Hi All,
    I have to group a few columns in the excel so that they can be expanded or collapsed. I am transforming an internal table into XML using Simple transformation. In this XSLT, I need to add the code to group the particular columns together in the final excel.
    Can any one please help me in acheiving the columns grouped together.
    Thanks and Regards,
    Vishnu.
    Edited by: Vishnu Kare on Mar 24, 2011 7:22 AM

    Hi Vishnu, I am also using simple transformations (not XSLT) to create XML excel from SAP data. I always create a template excel workbook from excel by saving it as XML file. This XML can be pasted into the SAP transformation without completely understanding the Microsoft excel syntax. The dynamic SAP data then can be included to the XML in the transformation.
    Regards Jack

  • Auto fit-width of form on open

    I have created a fillable form that has an orientation of landscape.  When we open it in Internet Explorer, it fits the entire form in the browser instead of doing a "fit width".  This causes my users to have to fit it to the width in IE manually.  Some of my users have a screen resolution of 1024 x 768 and some have a screen resolution of 800 x 600.  I would like to force a "fit width" when anyone opens the form in IE.  How can I force that?  If this requires programming code I will need specifics.  Thanks!

    Hi,
    No; I would not recommend inserting script directly into the XML Source tab. You rarely have to go in here.
    If you go to the Design view and select on of the objects in your form (TextField, numericField, etc). Then check that your Script Editor is open, it should be visible at the top of the window, just below the menu and toolbars. It may only be one line high, if that is the case then drag the bottom bar to make it bigger.
    If you cannot see the Script Editor, then you can open in from the Window menu or select Control+Shift+F5.
    When you select an object, you can go to the Script Editor and select from the dropdown which event you want to script for. In this case we are looking for the Initialize event. The script is Javascript so you need to check that in the language dropdown. Also unless you are using a server solution, your scripts will run at Client.
    You can put in the script into the Script Editor.
    Hope that helps,
    Niall

  • Insert a Picture into the Picture/Image Content Control using Open XML SDK 2.0

    I have created a word template as follows
    Here PizzaPicture is a Picture Content Control, PizzaName is a Plain Text Content Control and PizzaDescription is a Rich Text Content Control
    I am able to assign text to PizzaName and PizzaDescription Easily but not able to even locate the PizzaPicture. Here is my code
    using (WordprocessingDocument document = WordprocessingDocument.Open(@".\test.docx", true)) {
    MainDocumentPart mainPart = document.MainDocumentPart;
    DocumentFormat.OpenXml.Wordprocessing.Text text = null;
    SdtContentBlock pizzaNameBlock = null;
    SdtContentBlock pizzaDescriptionBlock = null;
    //SdtContentBlock pizzaPictureBlock = null;
    List<SdtBlock> sdtList = mainPart.Document.Descendants<SdtBlock>().ToList();
    foreach (SdtBlock sdt in sdtList)
    Console.WriteLine(sdt.SdtProperties.GetFirstChild<Tag>().Val.Value);
    SdtBlock s1 = mainPart.Document.Body.Descendants<SdtBlock>().Where(r => r.SdtProperties.GetFirstChild<Tag>().Val == "PizzaName").Single();
    SdtBlock s2 = mainPart.Document.Body.Descendants<SdtBlock>().Where(r => r.SdtProperties.GetFirstChild<Tag>().Val == "PizzaDescription").Single();
    SdtBlock s3 = mainPart.Document.Body.Descendants<SdtBlock>().FirstOrDefault(r =>
    SdtProperties p = r.Elements<SdtProperties>().FirstOrDefault();
    if (p != null)
    Console.WriteLine("P is not null");
    // Is it a picture content control?
    SdtContentPicture pict =
    p.Elements<SdtContentPicture>().FirstOrDefault();
    if (pict != null) Console.WriteLine("Pict is not null");
    // Get the alias.
    SdtAlias a = p.Elements<SdtAlias>().FirstOrDefault();
    if (pict != null && a.Val == "PizzaPicture")
    return true;
    return false;
    if (s3 == null) {
    Console.Write(" s3 is Null");
    } else {
    Console.WriteLine("s3 not null");
    if (s1 != null) {
    pizzaNameBlock = s1.Descendants<SdtContentBlock>().FirstOrDefault();
    text = pizzaNameBlock.Descendants<DocumentFormat.OpenXml.Wordprocessing.Text>().FirstOrDefault();
    // here you can set the current time
    text.Text = "Peperoni";
    Console.WriteLine(text.Text);
    string embed = null;
    if (s3 != null)
    Drawing dr = s3.Descendants<Drawing>().FirstOrDefault();
    if (dr != null)
    Blip blip = dr.Descendants<Blip>().FirstOrDefault();
    if (blip != null)
    embed = blip.Embed;
    if (embed != null)
    IdPartPair idpp = document.MainDocumentPart.Parts
    .Where(pa => pa.RelationshipId == embed).FirstOrDefault();
    if (idpp != null)
    ImagePart ip = (ImagePart)idpp.OpenXmlPart;
    using (FileStream fileStream =
    File.Open(@"c:\temp\pepperoni.jpg", FileMode.Open))
    ip.FeedData(fileStream);
    if (s2 != null) {
    pizzaDescriptionBlock = s2.Descendants<SdtContentBlock>().FirstOrDefault();
    string altChunkId = "AltChunkId12345";
    AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Xhtml, altChunkId);
    chunk.FeedData(File.Open(@".\html.txt", FileMode.Open));
    AltChunk altChunk = new AltChunk();
    altChunk.Id = altChunkId;
    ////Replace content control with altChunk information
    OpenXmlElement parent = pizzaDescriptionBlock.Parent;
    parent.InsertAfter(altChunk, pizzaDescriptionBlock);
    pizzaDescriptionBlock.Remove();
    mainPart.Document.Save();
    document.Close();
    Here the call mainPart.Document.Descendants<SdtBlock>().ToList(); returns me only 2 items PizzaName, PizzaDescription but
    no PizzaPicture.
    Secondly the line   SdtContentPicture pict =  p.Elements<SdtContentPicture>().FirstOrDefault();
    returns NULL. So it seems that there is no element of type SdtContentPicture.
    What am I doing wrong? I am pretty sure that I have put PizzaPicture as a Picture content control.
    My objective is to locate this control in the document and then insert an image into it programmatically.
    MSDNStudent Knows not much!

    Hi,
    I'm running some test on your code, and I'll come back as soon as I get some update. But before that, I would recommend you to bind customXMLPart with the content controls via Content Control Tool Kit,
    which enables us to bind customXMLPart with CC by dragging and dropping.
    After binding, you can change contents of the template via OpenXML SDK easily as the following code:
    private void button1_Click(object sender, EventArgs e)
    string fileName = @"C:\CCTest.docx";
    WordprocessingDocument wordDoc = WordprocessingDocument.Open(fileName, true);
    MainDocumentPart mainPart = wordDoc.MainDocumentPart;
    CustomXmlPart customPart = mainPart.CustomXmlParts.FirstOrDefault();
    //convert image into string
    string picName = @"C:\Users\Public\Pictures\Sample Pictures\Desert.jpg";
    System.IO.FileStream fileStream = System.IO.File.Open(picName, System.IO.FileMode.Open);
    System.IO.BinaryReader br = new System.IO.BinaryReader(fileStream);
    byte[] byteArea;
    byteArea = br.ReadBytes(System.Convert.ToInt32(fileStream.Length));
    string picString = System.Convert.ToBase64String(byteArea);
    //Load the XML template
    string DataString = Properties.Resources.XMLData;
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.LoadXml(DataString);
    //change the value
    XmlNodeList xmlNode = xmlDoc.GetElementsByTagName("pizzaPic");
    xmlNode[0].InnerText = picString;
    xmlNode = xmlDoc.GetElementsByTagName("pizzaName");
    xmlNode[0].InnerText = "Pizza Name";
    xmlNode = xmlDoc.GetElementsByTagName("pizzaDescription");
    xmlNode[0].InnerText = "Pizza Description";
    //write the custom xml data into the customxmlpart
    System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(customPart.GetStream(System.IO.FileMode.Create), System.Text.Encoding.UTF8);
    writer.WriteRaw(xmlDoc.InnerXml);
    writer.Flush();
    writer.Close();
    fileStream.Close();
    br.Close();
    mainPart.Document.Save();
    wordDoc.Close();
    and the XML template of the project would something like:
    <?xml version="1.0"?>
    <Pizza xmlns="http://Test/ContentControls/Pizzas">
    <pizzaPic></pizzaPic>
    <pizzaName></pizzaName>
    <pizzaDescription></pizzaDescription>
    </Pizza>
    I hope this helps.
    Calvin Gao[MSFT]
    MSDN Community Support | Feedback to us

  • How do I autosize columns in Excel using ActiveX in Labview

    I found the ExcelExamples.llb but nothing that describes this. My data is sometimes bigger than the default column width.
    thanks

    How about using a macro to run the column autosize function?
    I cheated, and recorded an autosize operation on a column, and then looked at the vb code behind the macro...
    Columns("D").EntireColumn.AutoFit
    should do the trick.
    In the excelexamples.llb, they seem to use macros to perform other functions, so maybe this is a way to achieve the autosize function that you require.
    Hope this helps...
    JB

  • Insert Pie Chart to Excel Using OpenXml

    I managed to implement the code(I got from MSDN) to create a bar graph in excel, I am however facing challenges in creating a piechart, I had thought that I can manipulate the code a little bit and  produce a pie chart-but I have spent nights and
    nights still can't find my way to create a pie chart. I need help on this, I would appreciate if you can help me through this.
    F.Shumba

    Hi F.Shuba,
    From the description, you want to create a piechart using Open XML.
    A recommend way is that create a pie chart manually and use Open XML SDK 2.5 Productivity Tool to open this workbook. Then you can get the code for creaing the chart for reference.
    If you still have issue, please feel free to let me know.
    Regards & Fei
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • How to save a selected word image to image file in open XML in PNG format?

    Hi Everyone,
    I have a very strange problem. I want to extract the image from word using open xml sdk. Here the user selects the image on opened word, and then clicks on any button, so it should extract the same selected image to any predefined location in the PNG format.
    I also tried to do the same thing using Word API, there I am copying the selection of image to clipboard and then getting the image and converting it to bitmap and saving it, but the image resolution is coming very bad. Is there any method through which
    I can save the image to file either by Open XML sdk or Word API using C#.
    Thanks,
    Shahab Abbasi

    Hi Shahab,
    To extract images from word document, please take a look at this thread:
    https://social.msdn.microsoft.com/Forums/office/en-US/e2a795ea-2ab7-401e-b6a8-0576220553f8/openxml-excel-how-to-extract-only-image-files?forum=oxmlsdk
    string fileName = @"C:\test.docx";
    using (WordprocessingDocument document = WordprocessingDocument.Open(fileName, true))
    var e = document.MainDocumentPart.ImageParts.GetEnumerator();
    int picNum = 0;
    while (e.MoveNext())
    picNum++;
    ImagePart imagePart = e.Current;
    Stream stream = imagePart.GetStream();
    long length = stream.Length;
    byte[] byteStream = new byte[length];
    stream.Read(byteStream, 0, (int)length);
    FileStream fstream = new FileStream(@"C:\abc.jpg", FileMode.OpenOrCreate);
    fstream.Write(byteStream, 0, (int)length);
    fstream.Close();
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Alignment of Columns in Excel when sent as an attachement

    Hi,
    I am using below code to send the output of ALV via email as an attachment.
    data : lv_variant type sy-slset value 'VARIANT',
             lt_list   type table of abaplist,
             lt_0167_body type standard table of soli,
             ls_body_raw type soli,
             lt_txt type soli_tab.
    data:   ls_string type text2048,
              lt_objbin type soli_tab,"Attachment of EMail
              lt_objbinx type solix_tab,"Attachment of EMail
              lv_dlist type so_obj_nam,
              lv_bdate type char10,
              lv_edate type char10,
              lv_title type char40.
    submit ztest using selection-set lv_variant exporting list to memory and return.
    call function 'LIST_FROM_MEMORY'
      tables
        listobject = lt_list "Binary data
      exceptions
        not_found  = 1.
    call function 'LIST_TO_TXT'
      tables
        listtxt            = lt_txt
        listobject         = lt_list
      exceptions
        empty_list         = 1
        list_index_invalid = 2
        others             = 3.
    if sy-subrc <> 0.
    * MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    *         WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    endif.
    move 'test' to ls_body_raw.
    append ls_body_raw to lt_0167_body.
    lt_0167_body[] = lt_0167_body[].
    data :
        l_hex type solix,
        conv type ref to cl_abap_conv_out_ce,
        l_buffer type xstring,
        l_hexa(510) type x.
      loop at lt_txt   into ls_string.
        conv = cl_abap_conv_out_ce=>create( encoding = 'UTF-8' endian = 'B').
        call method conv->write( data = ls_string ).
        l_buffer = conv->get_buffer( ).
        move l_buffer to l_hexa.
        move l_hexa to l_hex-line.
        append l_hex to lt_objbinx.
      endloop.
    call method ztest=>send_mail
      exporting
        it_errormessages     = lt_0167_body
        iv_type              = 'RAW'
        iv_dist_list         = 'DLIST' "distribution list
        iv_subject           =  'test'
        lv_attachment_type   = 'XLS'
        lv_attachment        = lt_objbinx
        lv_attachment_name   = 'Test'
      exceptions
        bcs_fault            = 1
        tvarv_not_maintained = 2
        others               = 3
    here my custom method send_mail is working properly it is sending whatever is coming in lt_objbinx as  excel, only problem in the excel columns and column values are not aligned properly.
    please suggest how can i align columns inside excel using abap code, send mail is actaully using cl_bcs and related classes for sending e-mail.
    Thanks,
    kranthi.

    Hi change the below sample as per your requirement.
    <unreadable code removed by moderator>
    Regards
    chitra
    Moderator message: please post only relevant code parts, your posts must contain less than 5000 characters to preserve readable formatting.
    Edited by: Thomas Zloch on Nov 15, 2011 1:03 PM

Maybe you are looking for