Main Content

writetable

Write table to file

Description

writetable(T) writes table T to a comma delimited text file. The file name is the workspace variable name of the table, appended with the extension .txt. If writetable cannot construct the file name from the input table name, then it writes to the file table.txt.

For text and spreadsheet files, each column of each variable in T becomes a column in the output file. The variable names of T become column headings in the first line of the file.

For XML files, each column in T becomes an XML node in the output file. The variable names of T become the names of the element nodes in the output XML file.

example

writetable(T,filename) writes to a file with the name and extension specified by filename.

writetable determines the file format based on the specified extension. The extension must be one of the following:

  • .txt, .dat, or .csv for delimited text files

  • .xls, .xlsm, or .xlsx for Excel® spreadsheet files

  • .xlsb for Excel spreadsheet files supported on systems with Excel for Windows®

  • .xml for Extensible Markup Language (XML) files

writetable(___,Name,Value) writes the table to a file with additional options specified by one or more Name,Value pair arguments and can include any of the input arguments in previous syntaxes.

For example, you can specify whether to write the variable names as column headings in the output file.

example

Examples

collapse all

Create a table.

T = table(['M';'F';'M'],[45 45;41 32;40 34],...
    {'NY';'CA';'MA'},[true;false;false])
T=3×4 table
    Var1      Var2       Var3     Var4 
    ____    ________    ______    _____

     M      45    45    {'NY'}    true 
     F      41    32    {'CA'}    false
     M      40    34    {'MA'}    false

Write the table to a comma delimited text file and display the file contents.

writetable(T)

writetable outputs a text file named T.txt.

type 'T.txt'
Var1,Var2_1,Var2_2,Var3,Var4
M,45,45,NY,1
F,41,32,CA,0
M,40,34,MA,0

writetable appends a unique suffix to the variable name, Var2, above the two columns of corresponding data.

Create a table.

T = table(['M';'F';'M'],[45 45;41 32;40 34],...
    {'NY';'CA';'MA'},[true;false;false])
T=3×4 table
    Var1      Var2       Var3     Var4 
    ____    ________    ______    _____

     M      45    45    {'NY'}    true 
     F      41    32    {'CA'}    false
     M      40    34    {'MA'}    false

Write the table to a space-delimited text file named myData.txt and display the file contents.

writetable(T,'myData.txt','Delimiter',' ')  
type 'myData.txt'
Var1 Var2_1 Var2_2 Var3 Var4
M 45 45 NY 1
F 41 32 CA 0
M 40 34 MA 0

writetable appends a unique suffix to the variable name, Var2, above the two columns of corresponding data.

Create a table.

LastName = {'Smith';'Johnson';'Williams';'Jones';'Brown'};
Age = [38;43;38;40;49];
Height = [71;69;64;67;64];
Weight = [176;163;131;133;119];
BloodPressure = [124 93; 109 77; 125 83; 117 75; 122 80];

T = table(Age,Height,Weight,BloodPressure,...
    'RowNames',LastName)
T=5×4 table
                Age    Height    Weight    BloodPressure
                ___    ______    ______    _____________

    Smith       38       71       176       124     93  
    Johnson     43       69       163       109     77  
    Williams    38       64       131       125     83  
    Jones       40       67       133       117     75  
    Brown       49       64       119       122     80  

Write the table, T, to a comma delimited text file, called myPatientData.dat, and display the file contents.

writetable(T,'myPatientData.dat','WriteRowNames',true)  
type 'myPatientData.dat'
Row,Age,Height,Weight,BloodPressure_1,BloodPressure_2
Smith,38,71,176,124,93
Johnson,43,69,163,109,77
Williams,38,64,131,125,83
Jones,40,67,133,117,75
Brown,49,64,119,122,80

The first column, which contains the row names, has the column heading, Row. This is the first dimension name for the table from the property T.Properties.DimensionNames.

Convert English dates in a table to German and write the table to file.

Create a table that contains a datetime array with dates in English. Create column vectors of numeric data to go with the dates.

D = datetime({'01-Jan-2014';'01-Feb-2014';'01-Mar-2014'});
D.Format = 'dd MMMM yyyy';
X1 = [20.2;21.6;20.7];
X2 = [100.5;102.7;99.8];
T = table(D,X1,X2)
T = 

           D             X1      X2  
    ________________    ____    _____

    01 January 2014     20.2    100.5
    01 February 2014    21.6    102.7
    01 March 2014       20.7     99.8

Write the table to a text file. Specify German for the locale of the dates using the DateLocale name-value pair argument, and display the dates in the text file.

writetable(T,'myfile.txt','DateLocale','de_DE');
type myfile.txt
D,X1,X2
01 Januar 2014,20.2,100.5
01 Februar 2014,21.6,102.7
01 März 2014,20.7,99.8

When your data contains foreign-language or non-ASCII characters, use the encoding parameter to ensure the file is written correctly. First, load the provided table into the workspace. Then, write the table to a file using the default encoding. Finally, write the table using 'UTF-8' encoding and examine the result.

Load Table_Japanese_Characters.mat which contains a table T. A preview of the table is shown below. Notice that the table contains two columns with Japanese characters.

load('Table_Japanese_Characters.mat')

Write the table to a file. The writetable function uses your system default encoding when writing files. Results may differ based on your system settings. To examine the resulting file, read the table back into the workspace by using the readtable function. Notice that writetable did not succeed in writing columns (1 and 3) containing foreign-language characters.

writetable(T,'myTable.txt')
myTable = readtable('myTable.txt')
myTable=9×3 table
      A        B          C   
    _____    ______    _______

    ''     458.98    ''  
    ''     530.14    ''  
    ''      289.4    ''  
    ''      434.81    ''
    ''    186.44    '' 
    ''           0    ''   
    ''      231.29    ''
    ''      311.86    ''
    ''     239.93    ''   

If your table contains foreign-language or non-ASCII characters, you must use the 'Encoding' parameter to ensure your data is written correctly. Set 'Encoding' to 'UTF-8' which supports a wide range of foreign-language and non-ASCII characters. To examine the resulting file, read the table back into the workspace by using the readtable function. With the correct encoding parameter the writetable function is successful in writing the data.

writetable(T,'myTable_UTF8.txt','Encoding','UTF-8')
myTable_UTF8 = readtable('myTable_UTF8.txt','Encoding','UTF-8')
myTable_UTF8=9×3 table
       A         B            C     
    _______    ______    ___________

    '南西'     458.98    '冬の嵐'    
    '南東'     530.14    '冬の嵐'    
    '南東'      289.4    '冬の嵐'    
    '西'       434.81    '機器の故障' 
    '中西部'    186.44    '深刻な嵐'  
    '西'            0    '攻撃'      
    '西'       231.29    '機器の故障' 
    '西'       311.86    '機器の故障' 
    '北東'     239.93    '火災'      

Create a table.

T = table(['M';'F';'M'],[45;41;36],...
    {'New York, NY';'San Diego, CA';'Boston, MA'},[true;false;false])
T=3×4 table
    Var1    Var2          Var3           Var4 
    ____    ____    _________________    _____

     M       45     {'New York, NY' }    true 
     F       41     {'San Diego, CA'}    false
     M       36     {'Boston, MA'   }    false

Write the table to a comma-separated text file named myData.csv and view the file contents. Use the 'QuoteStrings' name-value pair argument to ensure that the commas in the third column are not treated as delimiters.

writetable(T,'myData.csv','Delimiter',',','QuoteStrings','all')
type 'myData.csv'
Var1,Var2,Var3,Var4
"M",45,"New York, NY",1
"F",41,"San Diego, CA",0
"M",36,"Boston, MA",0

Create a table.

T = table(['M';'F';'M'],[45 45;41 32;40 34],...
    {'NY';'CA';'MA'},[true;false;false])
T=3×4 table
    Var1      Var2       Var3     Var4 
    ____    ________    ______    _____

     M      45    45    {'NY'}    true 
     F      41    32    {'CA'}    false
     M      40    34    {'MA'}    false

Write the table to a spreadsheet named myData.xls. Include the data on the first sheet in the 5-by-5 region with corners at B2 and F6. You can change the worksheet to write to by specifying the index corresponding to the worksheet.

writetable(T,'myData.xls','Sheet',1,'Range','B2:F6')

Excel® fills the row of the spreadsheet from B6 to F6 with #N/A since the range specified is larger than the size of the input table T.

You can write tabular data containing variable names that have any characters, including spaces and non-ASCII characters. Create a table with arbitrary variable names and write the table to a text file. Then, read the tabular data back while preserving the original variable names.

Create a table containing three variables with arbitrary variable names. The first and third variable names contain spaces and non-ASCII characters.

LastName = {'Sanchez';'Johnson';'Li';'Diaz';'Brown'};
Age = [38;43;38;40;49];
Smoker = logical([1;0;1;0;1]);
varNames = {'Last Name','Age','Smoker (1 or 0)'};
T = table(LastName,Age,Smoker,'VariableNames',varNames)
T=5×3 table
     Last Name     Age    Smoker (1 or 0)
    ___________    ___    _______________

    {'Sanchez'}    38          true      
    {'Johnson'}    43          false     
    {'Li'     }    38          true      
    {'Diaz'   }    40          false     
    {'Brown'  }    49          true      

Write the data to the file 'sampletable.txt'.

writetable(T,'sampletable.txt')

Read the tabular data back using readtable. By default, MATLAB® converts any variable names that include spaces and non-ASCII characters into valid MATLAB® identifiers. For example, MATLAB® converts the variable names 'Last Name' to 'LastName', and 'Smoker (1 or 0)' to 'Smoker_1or0_'. To read the tabular data while preserving variable names, set the 'VariableNamingRule' parameter to preserve.

T_preserve = readtable('sampletable.txt',"VariableNamingRule","preserve")
T_preserve=5×3 table
     Last Name     Age    Smoker (1 or 0)
    ___________    ___    _______________

    {'Sanchez'}    38            1       
    {'Johnson'}    43            0       
    {'Li'     }    38            1       
    {'Diaz'   }    40            0       
    {'Brown'  }    49            1       

Append data as a new row to the bottom of a table with existing data.

Create a table.

InsectSpecies = {'Monarch Butterfly';'Seven-spot Ladybird';'Orchid Mantis';...
    'American Bumblebee';'Blue Dasher Dragonfly'};
InsectOrder = {'Lepidoptera';'Coleoptera';'Mantodea';'Hymenoptera';'Odonata'};
InsectFamily = {'Nymphalidae';'Coccinellidae';'Hymenopodidae';...
    'Apidae';'Libellulidae'};
PredatoryInsect = logical([0;1;1;0;1]); 

T = table(InsectSpecies,InsectOrder,InsectFamily,PredatoryInsect)
T=5×4 table
          InsectSpecies            InsectOrder        InsectFamily       PredatoryInsect
    _________________________    _______________    _________________    _______________

    {'Monarch Butterfly'    }    {'Lepidoptera'}    {'Nymphalidae'  }         false     
    {'Seven-spot Ladybird'  }    {'Coleoptera' }    {'Coccinellidae'}         true      
    {'Orchid Mantis'        }    {'Mantodea'   }    {'Hymenopodidae'}         true      
    {'American Bumblebee'   }    {'Hymenoptera'}    {'Apidae'       }         false     
    {'Blue Dasher Dragonfly'}    {'Odonata'    }    {'Libellulidae' }         true      

Write the table T to a text file called InsectCollection.txt.

writetable(T,'InsectCollection.txt','WriteRowNames',true) 

Create new data in the form of a table to add to the existing table.

newInsect = table({'Red-banded leafhopper'},{'Hemiptera'},{'Cicadellidae'},logical([0]))
newInsect=1×4 table
              Var1                   Var2               Var3          Var4 
    _________________________    _____________    ________________    _____

    {'Red-banded leafhopper'}    {'Hemiptera'}    {'Cicadellidae'}    false

Append newInsect to InsectCollection.txt using the 'WriteMode','Append' name-value pair argument.

writetable(newInsect,'InsectCollection.txt','WriteMode','Append',...
    'WriteVariableNames',false,'WriteRowNames',true)  

Read the table back into the workspace.

readtable('InsectCollection.txt')
ans=6×4 table
          InsectSpecies            InsectOrder        InsectFamily       PredatoryInsect
    _________________________    _______________    _________________    _______________

    {'Monarch Butterfly'    }    {'Lepidoptera'}    {'Nymphalidae'  }           0       
    {'Seven-spot Ladybird'  }    {'Coleoptera' }    {'Coccinellidae'}           1       
    {'Orchid Mantis'        }    {'Mantodea'   }    {'Hymenopodidae'}           1       
    {'American Bumblebee'   }    {'Hymenoptera'}    {'Apidae'       }           0       
    {'Blue Dasher Dragonfly'}    {'Odonata'    }    {'Libellulidae' }           1       
    {'Red-banded leafhopper'}    {'Hemiptera'  }    {'Cicadellidae' }           0       

Preserve the existing column widths of a spreadsheet file when you append data to the bottom of the file.

Create workspace variables with text data, then create a table as a container for the variables.

state = {'Massachussetts';'California';'Minnesota';'Virginia'};
stateFlower = {'Trailing arbutus';'Golden Poppy';'Pink and White Lady''s Slipper';'Flowering dogwood'};
stateBird = {'Black-capped chickadee';'California Valley Quail';'Common Loon';'Cardinal'};
data = table(state,stateFlower,stateBird);

Write the table to a spreadsheet file named states_funfacts.xlsx.

writetable(data,'state_funfacts.xlsx')

Create another table of text data.

t = table({'Maryland';'New York'},{'Black-eyed Susan';'Rose'},{'Baltimore oriole';'Eastern bluebird'});

Append the table to the existing spreadsheet file. Specify 'AutoFitWidth' as false to preserve the existing column widths of the spreadsheet.

writetable(t,'state_funfacts.xlsx',"WriteMode","append","AutoFitWidth",false);

states_original.PNG

If you specify 'AutoFitWidth' as true instead of false, then writetable will adjust the column widths of the spreadsheet to fit the data to be written instead of preserving the original columns widths.

states_appended.PNG

Edit rows within an existing spreadsheet file without preserving the cell formatting of the spreadsheet.

The spreadsheet file student_grades.xlsx contains formatted cells. All the cells are color-filled and have borders, and the header cells have bold font.

Create a table with text and numeric data.

Student = {'Mary';'John'};
Grade = [95;87];
t = table(Student,Grade)
t=2×2 table
    Student     Grade
    ________    _____

    {'Mary'}     95  
    {'John'}     87  

Update the existing spreadsheet file with the table of input data. Specify 'PreserveFormat' as false to ignore the existing cell formatting of the spreadsheet file. When you do this, student_grades.xlsx is modified in the following way.

writetable(t,'student_grades.xlsx','PreserveFormat',false);

If you specify 'PreserveFormat' as true instead of false when you write the data to the existing spreadsheet file, writetable will preserve the existing cell formatting of the spreadsheet.

writetable(t,'student_grades.xlsx','PreserveFormat',true);

Create a table of data, then write it to an XML file. Customize how writetable writes table data to the XML file by specifying additional name-value arguments.

Create a table of data.

InsectSpecies = {'Monarch Butterfly';'Seven-spot Ladybird';'Orchid Mantis'; ...
    'American Bumblebee';'Blue Dasher Dragonfly'};
InsectOrder = {'Lepidoptera';'Coleoptera';'Mantodea';'Hymenoptera';'Odonata'};
InsectFamily = {'Nymphalidae';'Coccinellidae';'Hymenopodidae'; ...
    'Apidae';'Libellulidae'};
PredatoryInsect = logical([0;1;1;0;1]); 

T = table(InsectOrder,InsectFamily,PredatoryInsect);
T.Properties.RowNames = InsectSpecies;
head(T,5)
                               InsectOrder        InsectFamily       PredatoryInsect
                             _______________    _________________    _______________

    Monarch Butterfly        {'Lepidoptera'}    {'Nymphalidae'  }         false     
    Seven-spot Ladybird      {'Coleoptera' }    {'Coccinellidae'}         true      
    Orchid Mantis            {'Mantodea'   }    {'Hymenopodidae'}         true      
    American Bumblebee       {'Hymenoptera'}    {'Apidae'       }         false     
    Blue Dasher Dragonfly    {'Odonata'    }    {'Libellulidae' }         true      

Write the table T to an XML file called InsectCollection.xml. Specify 'WriteRowNames' as true to write the names of the table rows. The row names appear as fields belonging to the Row element node in the output XML file.

Customize the node names in the XML file by specifying 'Insect' as the value of 'RowNodeName'.

writetable(T,'InsectCollection.xml',"WriteRowNames",false,"RowNodeName","Insect")

Display the contents of the file InsectCollection.xml.

type InsectCollection.xml
<?xml version="1.0" encoding="UTF-8"?>
<table>
    <Insect>
        <InsectOrder>Lepidoptera</InsectOrder>
        <InsectFamily>Nymphalidae</InsectFamily>
        <PredatoryInsect>false</PredatoryInsect>
    </Insect>
    <Insect>
        <InsectOrder>Coleoptera</InsectOrder>
        <InsectFamily>Coccinellidae</InsectFamily>
        <PredatoryInsect>true</PredatoryInsect>
    </Insect>
    <Insect>
        <InsectOrder>Mantodea</InsectOrder>
        <InsectFamily>Hymenopodidae</InsectFamily>
        <PredatoryInsect>true</PredatoryInsect>
    </Insect>
    <Insect>
        <InsectOrder>Hymenoptera</InsectOrder>
        <InsectFamily>Apidae</InsectFamily>
        <PredatoryInsect>false</PredatoryInsect>
    </Insect>
    <Insect>
        <InsectOrder>Odonata</InsectOrder>
        <InsectFamily>Libellulidae</InsectFamily>
        <PredatoryInsect>true</PredatoryInsect>
    </Insect>
</table>

If you do not specify WriteRowNames as true, writetable skips writing the table row names to the file.

output.PNG

Input Arguments

collapse all

Input data, specified as a table.

File name, specified as a character vector or string scalar.

Depending on the location you are writing to, filename can take on one of these forms.

Location

Form

Current folder

To write to the current folder, specify the name of the file in filename.

Example: 'myTextFile.csv'

Other folders

To write to a folder different from the current folder, specify the full or relative path name in filename.

Example: 'C:\myFolder\myTextFile.csv'

Example: 'myFolder\myExcelFile.xlsx'

Remote Location

To write to a remote location, filename must contain the full path of the file specified as a uniform resource locator (URL) of the form:

scheme_name://path_to_file/my_file.ext

Based on the remote location, scheme_name can be one of the values in this table.

Remote Locationscheme_name
Amazon S3™s3
Windows Azure® Blob Storagewasb, wasbs
HDFS™hdfs

For more information, see Work with Remote Data.

Example: 's3://bucketname/path_to_file/my_file.xlsx'

  • If filename includes the file extension, then the writing function determines the file format from the extension. Otherwise, the writing function creates a comma separated text file and appends the extension .txt. Alternatively, you can specify filename without the file’s extension, and then include the 'FileType' name-value pair arguments to indicate the type of file.

  • If filename does not exist, then the writing function creates the file.

  • If filename is the name of an existing text file, then the writing function overwrites the file.

  • If filename is the name of an existing spreadsheet file, then the writing function writes the data to the specified location, but does not overwrite any values outside the range of the input data.

Data Types: char | string

Name-Value Arguments

Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN, where Name is the argument name and Value is the corresponding value. Name-value arguments must appear after other arguments, but the order of the pairs does not matter.

Before R2021a, use commas to separate each name and value, and enclose Name in quotes.

Example: 'WriteVariableNames',false indicates that the variable names should not be included as the first row of the output file.

All Supported File Types

collapse all

Indicator for writing row names, specified as the comma-separated pair consisting of 'WriteRowNames' and either false or true.

Indicator

Behavior

false

writetable does not include the row names from T in the output. This is the default behavior.

true

For text and spreadsheet files, writetable includes the row names from T as the first column of the output.

If both the 'WriteVariableNames' and 'WriteRowNames' logical indicators are true, then writetable uses the first dimension name from the property T.Properties.DimensionNames as the column heading for the first column of the output.

For XML files, writetable writes the row names of the input table as the first attribute node on each of the row nodes, and uses the first dimension name from the property T.Properties.DimensionNames as the name of the attribute node.

Locale for writing dates, specified as the comma-separated pair consisting of 'DateLocale' and a character vector or a string scalar. When writing datetime values to the file, use DateLocale to specify the locale in which writetable should write month and day-of-week names and abbreviations. The character vector or string takes the form xx_YY, where xx is a lowercase ISO 639-1 two-letter code indicating a language, and YY is an uppercase ISO 3166-1 alpha-2 code indicating a country. For a list of common values for the locale, see the Locale name-value pair argument for the datetime function.

The writing function ignores the 'DateLocale' parameter value whenever dates can be written as Excel-formatted dates.

Example: 'DateLocale','ja_JP'

Data Types: char | string

Type of file, specified as the comma-separated pair consisting of 'FileType' and a character vector or string containing 'text', 'spreadsheet', or 'xml'.

The 'FileType' name-value pair must be used with the filename input argument. You do not need to specify the 'FileType' name-value pair argument if the filename input argument includes a standard file extension. The following standard file extensions are recognized by the writing function:

  • .txt, .dat, or .csv for delimited text files

  • .xls, .xlsm, or .xlsx for Excel spreadsheet files

  • .xlsb for Excel spreadsheet files supported on systems with Excel for Windows

  • .xml for XML files.

Example: 'FileType','spreadsheet'

Data Types: char | string

Text and Spreadsheet Files

collapse all

Indicator for writing variable names as column headings, specified as the comma-separated pair consisting of 'WriteVariableNames' and either true or false.

Indicator

Behavior

true

The writing function includes variable names as the column headings of the output. This is the default behavior.

false

The writing function does not include variable names in the output.

Writing mode, specified as the comma-separated pair consisting of 'WriteMode' and a character vector or a string scalar. Select a write mode based on the file type.

File Type

Write Mode

Text Files

  • 'overwrite' (default) — Overwrite the file.

  • 'append' — Append data to the file.

If the file you specified does not exist, then the writing function creates and writes data to a new file.

Spreadsheet Files

  • 'inplace' (default) — Update only the range occupied by the input data. The writing function does not alter any data outside of the range occupied by the input data.

    • If you do not specify a sheet, then the writing function writes to the first sheet.

  • 'overwritesheet' — Clear the specified sheet and write the input data to the cleared sheet.

    • If you do not specify a sheet, then the writing function clears the first sheet and writes the input data to it.

  • 'append' — The writing function appends the input data to the bottom of the occupied range of the specified sheet.

    • If you do not specify a sheet, then the writing function appends the input data to the bottom of the occupied range of the first sheet.

  • 'replacefile' — Remove all other sheets from the file, then clear and write the input data to the to the specified sheet.

    • If you do not specify a sheet, then the writing function removes all other sheets from the file, and then clears and writes the input data to the first sheet.

    • If the file you specified does not exist, then the writing function creates a new file and writes the input data to the first sheet.

  • When WriteVariableNames is set to true, the writing function does not support the write mode 'append'.

  • For spreadsheet files:

    • When the write mode is 'append', the writing function does not support the Range parameter.

    • If the file you specified does not exist, then the writing function performs the same actions as 'replacefile'.

Example: 'WriteMode','append'

Data Types: char | string

Text and XML Only

collapse all

Character encoding scheme associated with the file, specified as the comma-separated pair consisting of 'Encoding' and 'system' or a standard character encoding scheme name. When you do not specify any encoding, the writing function uses UTF-8 to write the file.

Example: 'Encoding','UTF-8' uses UTF-8 as the encoding.

Data Types: char | string

Text Files Only

collapse all

Field delimiter character, specified as the comma-separated pair consisting of 'Delimiter' and a character vector or string scalar containing one of these specifiers:

Specifier

Field Delimiter

','

'comma'

Comma. This is the default behavior.

' '

'space'

Space

'\t'

'tab'

Tab

';'

'semi'

Semicolon

'|'

'bar'

Vertical bar

You can use the 'Delimiter' name-value pair only for delimited text files.

Example: 'Delimiter','space'

Data Types: char | string

Indicator for writing quoted text, specified as "minimal", "all", or "none".

  • If QuoteStrings is "minimal", then the function encloses any variables containing the delimiter, line ending, or double-quote character in double-quote characters.

  • If QuoteStrings is "all", then the function encloses all text, categorical, datetime, and duration variables in double-quote characters.

  • If QuoteStrings is "none", then the function does not enclose variables in double-quote characters.

You can use the QuoteStrings name-value argument only with delimited text files.

Spreadsheet Files Only

collapse all

Worksheet to write to, specified as the comma-separated pair consisting of 'Sheet' and a character vector or a string scalar containing the worksheet name or a positive integer indicating the worksheet index. The worksheet name cannot contain a colon (:). To determine the names of sheets in a spreadsheet file, use sheets = sheetnames(filename). For more information, see sheetnames.

Specify the worksheet to write to by name or index:

  • name — If the specified sheet name does not exist in the file, then the writing function adds a new sheet at the end of the worksheet collection.

  • index — If the specified sheet index is an index larger than the number of worksheets, then the writing function appends empty sheets until the number of worksheets in the workbook equals the sheet index. The writing function also generates a warning indicating that it has added a new worksheet.

You can use the 'Sheet' name-value pair only with spreadsheet files.

Example: 'Sheet',2

Example: 'Sheet', 'MySheetName'

Data Types: char | string | single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

Rectangular portion of worksheet to write to, specified as the comma-separated pair consisting of 'Range' and a character vector or string scalar in one of the following forms.

Form of the Value of Range Description
'Corner1'

Corner1 specifies the first cell of the region to write. The writing function writes the data starting at this cell.

Example: 'Range','D2'

'Corner1:Corner2'

Corner1 and Corner2 are two opposing corners that define the region to write. For example, 'D2:H4' represents the 3-by-5 rectangular region between the two corners D2 and H4 on the worksheet. The 'Range' name-value pair argument is not case sensitive, and uses Excel A1 reference style (see Excel help).

Example: 'Range','D2:H4'

  • If the range you specify is smaller than the size of the input data, then the writing function writes only a subset of the input data that fits into the range.

  • If the range you specify is larger than the size of the input data, then the writing function leaves the remainder of the region as it is.

The 'Range' name-value pair can only be used with Excel files.

Example: 'Range', 'A1:F10'

Data Types: char | string

Flag to start an instance of Microsoft Excel for Windows when writing spreadsheet data, specified as the comma-separated pair consisting of 'UseExcel' and either true, or false.

You can set the 'UseExcel' parameter to one of these values:

  • true — The writing function starts an instance of Microsoft Excel when writing the file.

  • false — The writing function does not start an instance of Microsoft Excel when writing the file. When operating in this mode, functionality for writing differs in the support of file formats and interactive features, such as formulas and macros.

UseExcel

true

false

Supported file formats

.xls, .xlsx, .xlsm, .xltx, .xltm, .xlsb, .ods

.xls, .xlsx, .xlsm, .xltx, .xltm

Support for interactive features, such as formulas and macros

Yes

No

When writing to spreadsheet files on Windows platforms, if you want to start an instance of Microsoft Excel, then set the 'UseExcel' parameter to true.

UseExcel is not supported in noninteractive, automated environments.

Automatically adjust column width, specified as true or false. If you specify a value of 0 or false, then writetable will not automatically adjust the column widths to fit the data in the cells.

Example: 'AutoFitWidth',0

Preserve cell formatting of existing spreadsheet, specified as true or false. If you specify false, writetable will not preserve the cell formatting of the spreadsheet. Formatting includes elements such as fonts, cell borders, and color-shaded cells.

When writing datetime data to a spreadsheet file, you must set both 'PreserveFormat' and the 'UseExcel' Name-Value pair to true to preserve the existing cell formatting. If 'UseExcel' is set to false and 'PreserveFormat' is set to true when writing datetime data to the file, writetable will not preserve the existing cell formatting of the file.

Example: 'PreserveFormat',false

XML Files Only

collapse all

Attribute suffix, specified as the comma-separated pair consisting of 'AttributeSuffix' and either a character vector or string scalar indicating which variable names in the input table to write as attributes in the output XML file.

For example, for a variable name AttName_att in the input table, you can specify 'AttributeSuffix','_att' to indicate that 'AttName' should be written out as an attribute in the output XML file.

  • If you do not specify 'AttributeSuffix', writetable defaults to writing variables with the suffix 'Attribute' as attributes in the output XML file.

  • If the attribute specified as the value of 'AttributeSuffix' matches the suffix appended to the variable name in the input table, the suffix will be dropped from the variable name in the output XML file. For example, if you specify 'AttributeSuffix','_att', a variable in the input table named MyField_att will correspond to the attribute named MyField in the XML file.

Example: 'AttributeSuffix','_att'

XML row node name, specified as the comma-separated pair consisting of 'RowNodeName' and either a character vector or string scalar the writing function writes as the node name in the output XML file that corresponds to the rows in the input table. If you do not specify RowNodeName, then the writing function writes 'row' as the name of the row nodes in the output table.

Example: 'TableNodeName','RootName'

XML root node name, specified as the comma-separated pair consisting of 'TableNodeName' and either a character vector or string scalar the writing function writes as the root node name in the output XML file. If you do not specify TableNodeName, then the writing function writes 'table' as the name of the root node in the output table.

Example: 'TableNodeName','RootName'

Limitations

  • writetable does not support writing nested tables. Use splitvars on the nested table to split multicolumn variables into single-column variables before writing.

Tips

  • Creating Empty Sheets in Spreadsheet Files: Create an empty sheet in a spreadsheet file using writetable by writing an empty table. For example, create an empty sheet named 'MySheetName'.

    writetable(table(),'empty.xls','Sheet','MySheetName')
    Or create three empty sheets called 'Sheet1', 'Sheet2', and 'Sheet3'.
     writetable(table(),'empty.xls','Sheet',3)

Algorithms

  • If both the 'WriteVariableNames' and 'WriteRowNames' logical indicators are true, then the writetable function uses the first dimension name from the property T.Properties.DimensionNames as the column heading for the first column of the output.

  • Excel converts Inf values to 65535. MATLAB® converts NaN, NaT, <undefined> categorical values, and <missing> string values to empty cells.

  • For Excel files, writetable writes table variables containing datetime arrays as Excel dates. If the table contains datetime arrays with years prior to either 1900 or 1904, then writetable writes the variables as text. For more information on Excel dates, see Differences between the 1900 and the 1904 date system in Excel.

  • There are some instances where the writetable function creates a file that does not represent T exactly. You will notice this when you use readtable to read that file. The resulting table might not have the same format or contents as the original table. If you need to save a table and retrieve it at a later time to match the original table exactly, with the same data and organization, then save it as a MAT-file. writetable writes an inexact table in the following instances:

    • When writing to text files, writetable outputs numeric variables using long g format, and categorical or character variables as unquoted characters.

    • For variables that have more than one column, writetable appends a unique identifier to the variable name to use as the column headings.

    • For output variables that have more than two dimensions, writetable outputs these variables as two dimensional where the trailing dimensions are collapsed. For example, writetable outputs a 4-by-3-by-2 variable as if its size were 4-by-6.

    • For variables with a cell data type, writetable outputs the contents of each cell as a single row, in multiple fields. If the contents are other than numeric, logical, character, or categorical, then writetable outputs a single empty field.

Version History

Introduced in R2013b