Write table to file - MATLAB writetable (2024)

Write table to file

collapse all in page

Syntax

writetable(T)

writetable(T,filename)

writetable(___,Name,Value)

Description

example

writetable(T) writestable T to a comma delimited text file. The filename is the workspace variable name of the table, appended with theextension .txt. If writetable cannotconstruct the file name from the input table name, then it writesto 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.

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

writetable determines the file format basedon 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 spreadsheetfiles supported on systems with Excel for Windows®

  • .xml for Extensible Markup Language (XML) files

example

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

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

Examples

collapse all

Write Table to Text File

Open Live Script

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,Var4M,45,45,NY,1F,41,32,CA,0M,40,34,MA,0

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

Write Table to Space-Delimited Text File

Open Live Script

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 Var4M 45 45 NY 1F 41 32 CA 0M 40 34 MA 0

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

Write Table to Text File Including Row Names

Open Live Script

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_2Smith,38,71,176,124,93Johnson,43,69,163,109,77Williams,38,64,131,125,83Jones,40,67,133,117,75Brown,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.

Write Foreign-Language Dates to Text File

Open Script

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,X201 Januar 2014,20.2,100.501 Februar 2014,21.6,102.701 März 2014,20.7,99.8

Write Foreign-Language Characters to Text Files

Open Live Script

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.

Write table to file - MATLAB writetable (1)

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 '火災' 

Write Quoted Text to CSV File

Open Live Script

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

Write Table to Specific Sheet and Range in Spreadsheet

Open Live Script

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.

Write Tabular Data Containing Arbitrary Variable Names

Open Live Script

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 to Bottom of Table

Open Live Script

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 Existing Column Widths

Open Live Script

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

Write table to file - MATLAB writetable (2)

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.

Write table to file - MATLAB writetable (3)

Modify Existing Cell Formatting

Open Live Script

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.

Write table to file - MATLAB writetable (4)

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

Write table to file - MATLAB writetable (5)

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

Write table to file - MATLAB writetable (6)

Write Table to XML File

Open Live Script

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.

Write table to file - MATLAB writetable (7)

Input Arguments

collapse all

TInput data
table

Input data, specified as a table.

filenameFile name
character vector | string scalar

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 indicatesthat the variable names should not be included as the first row ofthe output file.

All Supported File Types

collapse all

WriteRowNamesIndicator for writing row names
false (default) | true

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.

DateLocaleLocale for writing dates
character vector | string scalar

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

FileTypeType of file
'text' | 'spreadsheet' | 'xml'

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

WriteVariableNamesIndicator for writing variable names as column headings
true (default) | false

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.

WriteModeWriting mode
character vector | string scalar

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

EncodingCharacter encoding scheme
'UTF-8' (default) | 'ISO-8859-1' | 'windows-1251' | 'windows-1252' | ...

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

DelimiterField delimiter character
character vector | string scalar

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

QuoteStringsIndicator for writing quoted text
"minimal" (default) | "all" | "none"

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

SheetWorksheet to write to
character vector | string scalar | positive integer

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

RangeRectangular portion of worksheet to write to
character vector | string scalar

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

UseExcelFlag to start instance of Microsoft® Excel for Windows
false (default) | true

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.

AutoFitWidthAutomatically adjust column width
true (default) | false

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

PreserveFormatPreserve cell formatting
true (default) | false

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

AttributeSuffixAttribute suffix
'Attribute' (default) | character vector | string scalar

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'

RowNodeNameXML row node name
'row' | string array

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'

TableNodeNameXML root node name
'table' (default) | character vector | string array

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 valuesto 65535. MATLAB® converts NaN, NaT, <undefined> categoricalvalues, and <missing> string values to emptycells.

  • 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 functioncreates a file that does not represent T exactly.You will notice this when you use readtable toread that file. The resulting table might not have the same formator contents as the original table. If you need to save a table andretrieve it at a later time to match the original table exactly, withthe same data and organization, then save it as a MAT-file. writetable writesan inexact table in the following instances:

    • When writing to text files, writetable outputsnumeric variables using long g format, and categoricalor character variables as unquoted characters.

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

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

    • For variables with a cell datatype, writetable outputs the contents of each cellas a single row, in multiple fields. If the contents are other thannumeric, logical, character, or categorical, then writetable outputsa single empty field.

Version History

Introduced in R2013b

See Also

table | readtable | writecell | writetimetable | writematrix

MATLAB Command

You clicked a link that corresponds to this MATLAB command:

 

Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.

Write table to file - MATLAB writetable (8)

Select a Web Site

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

You can also select a web site from the following list:

Americas

  • América Latina (Español)
  • Canada (English)
  • United States (English)

Europe

  • Belgium (English)
  • Denmark (English)
  • Deutschland (Deutsch)
  • España (Español)
  • Finland (English)
  • France (Français)
  • Ireland (English)
  • Italia (Italiano)
  • Luxembourg (English)
  • Netherlands (English)
  • Norway (English)
  • Österreich (Deutsch)
  • Portugal (English)
  • Sweden (English)
  • Switzerland
    • Deutsch
    • English
    • Français
  • United Kingdom (English)

Asia Pacific

  • Australia (English)
  • India (English)
  • New Zealand (English)
  • 中国
  • 日本 (日本語)
  • 한국 (한국어)

Contact your local office

Write table to file - MATLAB writetable (2024)
Top Articles
Latest Posts
Article information

Author: Margart Wisoky

Last Updated:

Views: 5814

Rating: 4.8 / 5 (78 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Margart Wisoky

Birthday: 1993-05-13

Address: 2113 Abernathy Knoll, New Tamerafurt, CT 66893-2169

Phone: +25815234346805

Job: Central Developer

Hobby: Machining, Pottery, Rafting, Cosplaying, Jogging, Taekwondo, Scouting

Introduction: My name is Margart Wisoky, I am a gorgeous, shiny, successful, beautiful, adventurous, excited, pleasant person who loves writing and wants to share my knowledge and understanding with you.