Method: Excel::Workbook#save
- Defined in:
- lib/rexcel/workbook.rb
#save(path, source_reference = nil) ⇒ Object
Save the workbook.
The filename must end with
-
.xls
-
.xlsx
-
.xlm (Microsoft Office Word 2003 XML Format)
-
.csv
Examples:
WB = Excel::Workbook.new()
# fill WB
WB.save('testfile.xls')
WB.save('testfile.xlsx')
WB.save('testfile.xml')
Save with reference to xml file
You may create the Excel file based on a xml file.
The way Ruby Workbook -> xml -> xls is faster then the direct xls generation.
Example:
WB = Excel::Workbook.new()
# fill WB
WB.save('testfile.xml')
WB.save('testfile_xml.xls', 'testfile.xml')
Save with reference to csv file
You may create the Excel file based on a csv file.
-
This method is only possible for workbooks with only one worksheets.
-
Attention! You may get problems with field conversion.
-
Therefor the way Ruby Workbook -> xml -> xls is recommended.
Example:
WB = Excel::Workbook.new()
# fill WB
WB.save('testfile.csv')
WB.save('testfile_xml.xls', 'testfile.csv')
Save with implicit reference files
Instead the explicit usage of xml/csv-file, the save command can do it implicit
Example:
WB = Excel::Workbook.new()
# fill WB
WB.save('testfile_xml.xls', :via_xml)
WB.save('testfile_xml.xls', :via_csv)
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 |
# File 'lib/rexcel/workbook.rb', line 198 def save(path, source_reference = nil) case source_reference when :via_xml source_reference = path.sub(/\.[^\.]+/, '.xml') save(source_reference) when :via_csv source_reference = path.sub(/\.[^\.]+/, '.csv') save(source_reference) end @log.info("Save #{path}") expath = File.(path) #Excel needs absolute path expath.gsub!(/\//, '\\')# Save the workbook. / must be \ begin #different formats, see http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.xlfileformat.aspx case path when /xlsx$/ wb = prepare_xls(source_reference) @log.info("Save #{path}") wb.SaveAs(expath, 51) wb.Close when /xls$/ wb = prepare_xls(source_reference) @log.info("Save #{path}") wb.SaveAs(expath, -4143 ) #excel97_2003_format wb.Close when /xml$/ Save "Microsoft Office Word 2003 XML Format". Special rules: * The last CR must be deleted. Else Excel doesn't accept the xml * There must be a name space. The namespace must be used before its definition (Tag Workbook) ns = 'ss' #namespace File.open(path, 'w'){|f| f << build_excel_xml(ns) } when /csv$/ File.open(path, 'w'){|f| f << build_excel_csv() } else @log.fatal("Wrong filename, no xls/xlsx (#{path})") raise ArgumentError, "Wrong filename, no xls/xlsx (#{path})" end rescue WIN32OLERuntimeError => err @log.error("Error #{path} (Opened in Excel?) #{err}") end # Close the workbook end |