├── .gitignore ├── LICENSE ├── README.md ├── Xlsx-Erlang.iml ├── rebar ├── rebar.cmd ├── rebar.config ├── src ├── xlsx_reader.erl ├── xlsx_util.erl ├── xlsx_writer.erl ├── xlsxio.app.src ├── xlsxio.erl └── xlsxio_sup.erl └── xlsx └── t.xlsx /.gitignore: -------------------------------------------------------------------------------- 1 | .eunit 2 | deps 3 | *.o 4 | *.beam 5 | *.plt 6 | erl_crash.dump 7 | ebin 8 | rel/example_project 9 | .concrete/DEV_MODE 10 | .rebar 11 | .DS_Store 12 | .idea/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2017 Adrianx Lau 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Xlsx-Reader-Writer 2 | Reader & Writer for Xlsx in Erlang 3 | 4 | ## USAGE: 5 | ``` 6 | shell>git clone git@github.com:adrianx77/Xlsx-Reader-Writer.git 7 | shell>./rebar co 8 | shell>erl xlsxio -pa ebin -s xlsxio test 9 | shell>erl xlsxio -pa ebin -s xlsxio test2 10 | 11 | ``` 12 | 13 | 14 | ``` 15 | xlsx_reader:read(XlsxFile, RowHandler) 16 | 17 | XlsxFile : only support higher than excel 2003 ,could be .xlsx or .xlsxm 18 | RowHandler: callback function =>fun(SheetName,RowData) 19 | SheetName:Sheet Name 20 | RowData : true text list 21 | return : next_sheet | next_row | break 22 | next_sheet : ignor left rows ,continue process next sheet 23 | next_row : continue next row 24 | break : ignor next rows and sheets 25 | ``` 26 | so you can write such code: 27 | ``` 28 | test()-> 29 | XlsxFile = "xlsx/t.xlsx", 30 | RowHandler = 31 | fun(SheetName, [1 | Row]) -> 32 | io:format("~n~ts=====>~p | ", [SheetName, 1]), 33 | lists:foreach(fun(R)-> io:format("\t~ts",[R]) end,Row), 34 | next_row; 35 | (SheetName, [Line | Row]) -> 36 | io:format("~n~ts=====>~p | ", [SheetName, Line]), 37 | lists:foreach(fun(R)-> io:format("\t~ts",[R]) end,Row), 38 | next_sheet 39 | end, 40 | 41 | case xlsx_reader:read(XlsxFile,RowHandler) of 42 | {error,Reason}-> io:format("read error:~p~n",[Reason]); 43 | ok-> io:format("~n") 44 | end. 45 | ``` 46 | ``` 47 | use Writer should with 4 step 48 | Author should be iolist or binary ,if your data with unicode code bigger 49 | than 255 you shoud convert by unicode:characters_to_binary 50 | If CellData in Rows is string ,you should call unicode:characters_to_binary first. 51 | 52 | 1、xlsx_writer:create(XlsxFile,Author)=>XlsxHandle 53 | 2、xlsx_writer:create_sheet(Title,Rows)=>SheetHandle 54 | 3、xlsx_writer:add_sheet(XlsxHandle,SheetHandle)=> ok. 55 | 4、xlsx_writer:close(XlsxHandle). 56 | 57 | ``` 58 | ``` 59 | test2()-> 60 | XlsxFile = "xlsx/t2.xlsx", 61 | XlsxHandle = xlsx_writer:create(XlsxFile,"adrianx.lau@gmail.com"), 62 | SheetHandle = xlsx_writer:create_sheet("Hello",[[2,1,1,2],[3,2,2]]), %% no first line 63 | SheetHandle2 = xlsx_writer:create_sheet("Hello2",[[1,1,1,2],[4,2,2]]), %% ignor line 2,3 64 | xlsx_writer:add_sheet(XlsxHandle,SheetHandle), 65 | xlsx_writer:add_sheet(XlsxHandle,SheetHandle2), 66 | xlsx_writer:close(XlsxHandle). 67 | ``` 68 | 69 | ## Future 70 | I will add some prompt for writer. 71 | 72 | 我的Erlang技术交流QQ群:221307508 -------------------------------------------------------------------------------- /Xlsx-Erlang.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /rebar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adrianx77/Xlsx-Reader-Writer/7485fe1f506465d44b6b33e2189fb351c55d6b38/rebar -------------------------------------------------------------------------------- /rebar.cmd: -------------------------------------------------------------------------------- 1 | @echo off 2 | setlocal 3 | set rebarscript=%~f0 4 | escript.exe "%rebarscript:.cmd=%" %* 5 | -------------------------------------------------------------------------------- /rebar.config: -------------------------------------------------------------------------------- 1 | {require_min_otp_vsn, "R15"}. 2 | 3 | {cover_enabled, true}. 4 | 5 | {erl_opts, [ 6 | debug_info, 7 | {src_dirs, ["src"]} 8 | ]}. 9 | -------------------------------------------------------------------------------- /src/xlsx_reader.erl: -------------------------------------------------------------------------------- 1 | %%%------------------------------------------------------------------- 2 | %%% @author Adrianx Lau 3 | %%% @copyright (C) 2017, 4 | %%% @doc 5 | %%% 6 | %%% @end 7 | %%% Created : 20. 二月 2017 下午12:14 8 | %%%------------------------------------------------------------------- 9 | -module(xlsx_reader). 10 | -author("Adrianx Lau "). 11 | -include_lib("xmerl/include/xmerl.hrl"). 12 | 13 | %% API 14 | -export([read/3]). 15 | 16 | -record(xlsx_sheet, {id, name}). 17 | -record(xlsx_share, {id, string}). 18 | -record(xlsx_relation, {id, target, type}). 19 | 20 | -spec(read(XlsxFile :: string(),InputContext::term(), RowHandler :: atom() | function()) -> 21 | {error, Resaon :: atom()} | {error, Resaon :: string()} | 22 | {ok}). 23 | 24 | read(XlsxFile,InputContext, RowHandler) -> 25 | case zip:zip_open(XlsxFile, [memory]) of 26 | {error, Reason} -> {error, Reason}; 27 | {ok, ZipHandle} -> 28 | Result= read_memory(ZipHandle,InputContext, RowHandler), 29 | clear_xlsx_context(), 30 | zip:zip_close(ZipHandle), 31 | Result 32 | end. 33 | 34 | read_memory(XlsxZipHandle, InputContext,RowHandler) -> 35 | try 36 | process_sheetinfos(XlsxZipHandle), 37 | process_sharestring(XlsxZipHandle), 38 | process_relationhips(XlsxZipHandle), 39 | {_,OutContext} = process_sheet_table(XlsxZipHandle,InputContext, RowHandler), 40 | OutContext 41 | catch 42 | error:Reason -> {error, Reason} 43 | end. 44 | 45 | process_sharestring(ZipHandle) -> 46 | ShareStringFile = "xl/sharedStrings.xml", 47 | case zip:zip_get(ShareStringFile, ZipHandle) of 48 | {error, Reason} -> 49 | ErrorString = xlsx_util:sprintf("zip:zip_get ~p error:~p", [ShareStringFile, Reason]); 50 | {ok, ShareStrings} -> 51 | {_File, Binary} = ShareStrings, 52 | do_put_shareString(Binary) 53 | end. 54 | 55 | 56 | process_relationhips(ZipHandle) -> 57 | RelationFile = "xl/_rels/workbook.xml.rels", 58 | case zip:zip_get(RelationFile, ZipHandle) of 59 | {error, Reason} -> 60 | ErrorString = xlsx_util:sprintf("zip:zip_get ~p error:~p", [RelationFile, Reason]), 61 | error(ErrorString); 62 | {ok, Relationships} -> 63 | {_File, Binary} = Relationships, 64 | case xmerl_scan:string(binary_to_list(Binary)) of 65 | {ParsedDocRootEl, _Rest} -> 66 | Result = xmerl_xpath:string("Relationship ", ParsedDocRootEl), 67 | lists:foreach(fun(Relation) -> put_xlsx_relation(get_relationship_info(Relation)) end, Result); 68 | ExceptResult -> ErrorString = xlsx_util:sprintf("xmerl_scan:string error:~p", ExceptResult), 69 | error(ErrorString) 70 | end 71 | end. 72 | process_sheet_table(XlsxZipHandle,InputContext, RowHandler) -> 73 | lists:foldl( 74 | fun (_SheetInfo,{break,Context}) -> 75 | {break,Context}; 76 | (SheetInfo,{next_sheet,Context}) -> 77 | SheetId = SheetInfo#xlsx_sheet.id, 78 | SheetName = SheetInfo#xlsx_sheet.name, 79 | Relation = get_xlsx_relation(SheetId), 80 | TargetFile = "xl/" ++ Relation#xlsx_relation.target, 81 | case zip:zip_get(TargetFile, XlsxZipHandle) of 82 | {error, Reason} -> ErrorString = xlsx_util:sprintf("zip:zip_get ~p error:~p", [TargetFile, Reason]),error(ErrorString); 83 | {ok, {_FileName, SheetBinary}} -> 84 | process_sheet(SheetBinary, SheetName,RowHandler,Context) 85 | end 86 | end, {next_sheet,InputContext},get_xlsx_sheets()). 87 | 88 | 89 | process_sheet(SheetBinary, SheetName ,RowHandler,InputContext) -> 90 | case xmerl_scan:string(binary_to_list(SheetBinary)) of 91 | {ParsedDocRootEl, _Rest} -> 92 | XMLS = ParsedDocRootEl#xmlElement.content, 93 | Dimensions = xlsx_util:xmlElement_from_name('dimension', XMLS), 94 | ColumnCount = xlsx_util:get_column_count(xlsx_util:xmlattribute_value_from_name('ref', Dimensions)), 95 | XmlSheetDatas = xlsx_util:xmlElement_from_name('sheetData', XMLS), 96 | XmlRows = lists:filter( 97 | fun(XmlRow) -> 98 | case xlsx_util:is_record(XmlRow, 'xmlElement') of 99 | false -> false; 100 | true -> XmlRow#xmlElement.name =:= 'row' 101 | end 102 | end, XmlSheetDatas#xmlElement.content), 103 | 104 | DefData = lists:duplicate(ColumnCount + 1, ""), 105 | RHRes = lists:foldl( 106 | fun(_XmlRow, {next_sheet,Context}) -> 107 | {next_sheet,Context}; 108 | (_XmlRow, {break,Context}) -> 109 | {break,Context}; 110 | (XmlRow, {next_row,Context}) -> 111 | case get_row(XmlRow, DefData) of 112 | [] -> {next_row,Context}; 113 | NewData -> 114 | RowHandler(SheetName, NewData ,Context) 115 | end 116 | end, {next_row,InputContext}, XmlRows), 117 | case RHRes of 118 | {next_row,OutContext}-> {next_sheet,OutContext}; 119 | _-> RHRes 120 | end; 121 | ExceptResult -> 122 | ErrorString = xlsx_util:sprintf("xmerl_scan:string error:~p", ExceptResult), 123 | error(ErrorString) 124 | end. 125 | 126 | do_put_shareString(BinaryString) -> 127 | case xmerl_scan:string(binary_to_list(BinaryString)) of 128 | {ParsedDocRootEl, _Rest} -> 129 | XMLS = ParsedDocRootEl#xmlElement.content, 130 | FltNodes = lists:filter( 131 | fun(Node) -> 132 | element(#xmlElement.name, Node) =:= 'si' 133 | end, XMLS), 134 | TextList = lists:map( 135 | fun(Node) -> 136 | Elements = Node#xmlElement.content, 137 | lists:foldl( 138 | fun(Element, AccTxt) -> 139 | case xlsx_util:is_record(Element, xmlElement) of 140 | false -> AccTxt; 141 | true -> 142 | case Element#xmlElement.name of 143 | t -> get_element_text(Element); 144 | r -> 145 | TxtNode = xlsx_util:xmlElement_from_name('t', Element#xmlElement.content), 146 | AccTxt ++ get_element_text(TxtNode); 147 | _ -> 148 | AccTxt 149 | end 150 | end 151 | end, [], Elements) 152 | end, FltNodes), 153 | lists:foldl( 154 | fun(Txt, Id) -> 155 | put_xlsx_share(Id, Txt), 156 | Id + 1 157 | end, 0, TextList); 158 | ExceptResult -> 159 | ErrorString = xlsx_util:sprintf("xmerl_scan:string error:~p", ExceptResult), 160 | error(ErrorString) 161 | end. 162 | 163 | 164 | 165 | get_element_text(Element) -> 166 | IsRecord = xlsx_util:is_record(Element, xmlElement), 167 | if not IsRecord -> []; 168 | true -> 169 | if element(#xmlElement.name, Element) =:= 't' -> 170 | 171 | TextNodes = lists:filter( 172 | fun(Text) -> 173 | xlsx_util:is_record(Text, xmlText) 174 | end, 175 | Element#xmlElement.content), 176 | 177 | case TextNodes of 178 | [] -> []; 179 | _ -> lists:flatmap( 180 | fun(T) -> 181 | Text1 = element(#xmlText.value, T), 182 | Text1 183 | end, 184 | TextNodes) 185 | end 186 | end 187 | end. 188 | process_sheetinfos(ZipHandle) -> 189 | SheetFile = "xl/workbook.xml", 190 | case zip:zip_get(SheetFile, ZipHandle) of 191 | {error, Reason} -> 192 | ErrorString = xlsx_util:sprintf("zip:zip_get ~p error:~p", [SheetFile, Reason]), 193 | error(ErrorString); 194 | {ok, WorkBook} -> 195 | {_File, Binary} = WorkBook, 196 | case xmerl_scan:string(binary_to_list(Binary)) of 197 | {ParsedDocRootEl, _Rest} -> 198 | SheetInfos = xmerl_xpath:string("//sheet", ParsedDocRootEl), 199 | lists:foreach( 200 | fun(SheetInfoRaw) -> 201 | SheetInfo = sheetinfo_from_workbook(SheetInfoRaw), 202 | put_xlsx_sheet(SheetInfo) 203 | end, SheetInfos), 204 | ok; 205 | ExceptResult -> 206 | ErrorString = xlsx_util:sprintf("xmerl_scan:string error:~p", ExceptResult), 207 | error(ErrorString) 208 | end 209 | end. 210 | 211 | 212 | sheetinfo_from_workbook(SheetInfo) -> 213 | Attributes = SheetInfo#xmlElement.attributes, 214 | lists:foldl( 215 | fun(Attr, Acc) -> 216 | if Attr#xmlAttribute.name =:= 'r:id' -> 217 | Acc#xlsx_sheet{id = Attr#xmlAttribute.value}; 218 | Attr#xmlAttribute.name =:= 'name' -> 219 | Acc#xlsx_sheet{name = Attr#xmlAttribute.value}; 220 | true -> 221 | Acc 222 | end 223 | end, #xlsx_sheet{}, Attributes). 224 | 225 | get_relationship_info(Relation) -> 226 | Attributes = Relation#xmlElement.attributes, 227 | lists:foldl(fun(Attr, Acc) -> 228 | if Attr#xmlAttribute.name =:= 'Target' -> 229 | Acc#xlsx_relation{target = Attr#xmlAttribute.value}; 230 | Attr#xmlAttribute.name =:= 'Id' -> 231 | Acc#xlsx_relation{id = Attr#xmlAttribute.value}; 232 | Attr#xmlAttribute.name =:= 'Type' -> 233 | Acc#xlsx_relation{type = filename:basename(Attr#xmlAttribute.value)}; 234 | true -> 235 | Acc 236 | end 237 | end, #xlsx_relation{}, Attributes). 238 | 239 | 240 | get_row(XmlRow, DefaultList) -> 241 | XmlCells = lists:filter( 242 | fun(XmlCell) -> 243 | case xlsx_util:is_record(XmlCell, 'xmlElement') of 244 | false -> false; 245 | true -> XmlCell#xmlElement.name =:= 'c' 246 | end 247 | end, XmlRow#xmlElement.content), 248 | case XmlCells of 249 | [] -> []; 250 | [XmlCell1 | LeftXmlCells] -> 251 | {CellName1, CellValue1} = get_cell_info(XmlCell1), 252 | {X1, Y1} = xlsx_util:get_field_number(CellName1), 253 | RowDataWithKey = xlsx_util:take_nth_list(1, DefaultList, Y1), 254 | RowData1 = xlsx_util:take_nth_list(X1 + 1, RowDataWithKey, CellValue1), 255 | lists:foldl( 256 | fun(Cell, RowData) -> 257 | {CellName, CellValue} = get_cell_info(Cell), 258 | {X, _Y} = xlsx_util:get_field_number(CellName), 259 | xlsx_util:take_nth_list(X + 1, RowData, CellValue) 260 | end, RowData1, LeftXmlCells) 261 | end. 262 | 263 | 264 | get_subnode_text(SubName,XmlNode) -> 265 | case lists:keyfind(SubName, #xmlElement.name, XmlNode#xmlElement.content) of 266 | false -> []; 267 | SubNode -> 268 | case SubNode#xmlElement.content of 269 | [] -> []; 270 | XmlTexts -> 271 | NewList = 272 | lists:map( 273 | fun(T) -> 274 | Bin = unicode:characters_to_binary(T#xmlText.value, utf8), 275 | binary_to_list(Bin) 276 | end, XmlTexts), 277 | xlsx_util:str_normalize(lists:flatten(NewList)) 278 | end 279 | end. 280 | 281 | 282 | 283 | get_cell_info(XmlCell) -> 284 | CellName = xlsx_util:xmlattribute_value_from_name('r', XmlCell), 285 | CellValue = case xlsx_util:has_attribute_value( 't', "s",XmlCell) of %% 1: t="s" => shareString | 2: t="str" => String 286 | true -> 287 | NewCellValue = list_to_integer(get_subnode_text('v',XmlCell)), 288 | get_xlsx_share_string(NewCellValue); 289 | false -> 290 | case xlsx_util:has_attribute_value( 't', "b",XmlCell) of 291 | true-> case list_to_integer(get_subnode_text('v',XmlCell)) of 292 | 1-> "TRUE"; 293 | _-> "FALSE" 294 | end; 295 | false->get_subnode_text('v',XmlCell) 296 | end 297 | end, 298 | {CellName, CellValue}. 299 | 300 | %% 301 | %% xlsx inner helper 302 | %% 303 | put_xlsx_sheet(SheetInfo) -> 304 | case get({xlsx_inner_context, sheet}) of 305 | undefined -> put({xlsx_inner_context, sheet}, [SheetInfo]); 306 | SheetInfos -> put({xlsx_inner_context, sheet}, SheetInfos ++ [SheetInfo]) 307 | end. 308 | 309 | get_xlsx_sheets() -> 310 | case get({xlsx_inner_context, sheet}) of 311 | undefined -> []; 312 | SheetInfos -> SheetInfos 313 | end. 314 | 315 | get_xlsx_share_table() -> 316 | case get({xlsx_inner_context, share}) of 317 | undefined -> 318 | Tab = ets:new(share_string, [set, {keypos, #xlsx_share.id}]), 319 | put({xlsx_inner_context, share},Tab), 320 | Tab; 321 | Tab -> 322 | Tab 323 | end. 324 | 325 | put_xlsx_share(Id, String) -> 326 | Tab = get_xlsx_share_table(), 327 | ets:insert(Tab, #xlsx_share{id = Id, string = String}). 328 | 329 | get_xlsx_share_string(Id) -> 330 | Tab = get_xlsx_share_table(), 331 | case ets:lookup(Tab, Id) of 332 | [] -> ""; 333 | [Obj] -> Obj#xlsx_share.string 334 | end. 335 | %%%%%%%%% 336 | put_xlsx_relation(Relation) -> 337 | case get({xlsx_inner_context, relation}) of 338 | undefined -> put({xlsx_inner_context, relation}, [Relation]); 339 | OldRelations -> put({xlsx_inner_context, relation}, [Relation | OldRelations]) 340 | end. 341 | 342 | get_xlsx_relation(Id) -> 343 | case get({xlsx_inner_context, relation}) of 344 | undefined -> false; 345 | Relations -> lists:keyfind(Id, #xlsx_relation.id, Relations) 346 | end. 347 | clear_xlsx_context() -> 348 | erlang:erase({xlsx_inner_context, sheet}), 349 | Tab = get_xlsx_share_table(), 350 | ets:delete(Tab), 351 | erlang:erase({xlsx_inner_context,relation}), 352 | erlang:erase({xlsx_inner_context, share}). 353 | -------------------------------------------------------------------------------- /src/xlsx_util.erl: -------------------------------------------------------------------------------- 1 | %%%------------------------------------------------------------------- 2 | %%% @author Adrianx Lau 3 | %%% @copyright (C) 2017, 4 | %%% @doc 5 | %%% 6 | %%% @end 7 | %%% Created : 22. 二月 2017 上午10:38 8 | %%%------------------------------------------------------------------- 9 | -module(xlsx_util). 10 | -author("Adrianx Lau "). 11 | -include_lib("xmerl/include/xmerl.hrl"). 12 | %% API 13 | -compile(export_all). 14 | -define(MIN_EXP, -1074). 15 | -define(FLOAT_BIAS, 1022). 16 | -define(BIG_POW, 4503599627370496). 17 | 18 | sprintf(Format,Args)-> 19 | lists:flatten(io_lib:format(Format,Args)). 20 | 21 | is_record(Term, RecordTag) when is_tuple(Term) -> 22 | element(1, Term) =:= RecordTag; 23 | is_record(_Term, _RecordTag)-> false. 24 | 25 | 26 | 27 | has_attribute_value( AttrName, AttValue,XmlNode) -> 28 | lists:any(fun(Attr) -> (Attr#xmlAttribute.name =:= AttrName) and 29 | (Attr#xmlAttribute.value =:= AttValue) 30 | end, XmlNode#xmlElement.attributes). 31 | 32 | xmlattribute_value_from_name(Name, XmlNode) -> 33 | case lists:keyfind(Name,#xmlAttribute.name,XmlNode#xmlElement.attributes) of 34 | false-> error(sprintf("xmlattribute_value_from_name exception: ~p ~p",[Name,XmlNode])); 35 | Attribute-> Attribute#xmlAttribute.value 36 | end. 37 | 38 | xmlElement_from_name(Name,XmlNode)-> 39 | case lists:keyfind(Name,#xmlElement.name,XmlNode) of 40 | false-> error(sprintf("xmlElement_from_name exception: ~p ~p",[Name,XmlNode])); 41 | Element-> Element 42 | end. 43 | 44 | 45 | 46 | get_column_count(DimString) -> 47 | [_BeginStr, EndStr] = case string:tokens(DimString, ":") of 48 | [BeginString, EndString] -> [BeginString, EndString]; 49 | [BeginString] -> [BeginString, BeginString] 50 | end, 51 | [End] = string:tokens(EndStr, "0123456789"), 52 | field_to_num(End). 53 | 54 | 55 | -define(APHALIC_LENGTH, ($Z - $A + 1) ). 56 | 57 | get_column_string(Column)-> 58 | lists:reverse(do_get_column_string(Column)). 59 | 60 | do_get_column_string(Column)when Column < ?APHALIC_LENGTH -> 61 | [$A + Column ]; 62 | do_get_column_string(Column)-> 63 | [ $A + Column rem ?APHALIC_LENGTH | do_get_column_string(( Column div ?APHALIC_LENGTH) -1)]. 64 | 65 | int_pow(_Base, 0) -> 66 | 1; 67 | int_pow(Base, Exp) when Exp> 0 -> 68 | int_pow(Base, Exp, 1). 69 | 70 | 71 | int_pow(Base, Exp, R) when Exp < 2 -> 72 | R * Base; 73 | int_pow(Base, Exp, R) -> 74 | int_pow(Base * Base, Exp bsr 1, case Exp band 1 of 1 -> R * Base; 0 -> R end). 75 | 76 | field_to_num(NumStr) -> 77 | {_, Num} = lists:foldr( 78 | fun(C, {I, N}) -> 79 | New = (C - $A + 1) * int_pow( $Z - $A + 1,I) + N, 80 | {I + 1, New} 81 | end, {0, 0}, NumStr), 82 | Num. 83 | 84 | get_field_number(FieldString)-> 85 | [FieldName] = string:tokens(FieldString, "0123456789"), 86 | PostNumString = string:right(FieldString, length(FieldString) - length(FieldName)), 87 | {field_to_num(FieldName), list_to_integer(PostNumString)}. 88 | 89 | %% @spec int_ceil(F::float()) -> integer() 90 | %% @doc Return the ceiling of F as an integer. The ceiling is defined as 91 | %% F when F == trunc(F); 92 | %% trunc(F) when F < 0; 93 | %% trunc(F) + 1 when F > 0. 94 | int_ceil(X) -> 95 | T = trunc(X), 96 | case (X - T) of 97 | Pos when Pos > 0 -> T + 1; 98 | _ -> T 99 | end. 100 | 101 | get_field_string(Column,Row)-> 102 | [get_column_string(Column) , integer_to_list(Row)]. 103 | 104 | take_nth_list(N, List, Value)-> 105 | {NewList, _Acc} = lists:mapfoldl( 106 | fun(Item, Index)-> 107 | if Index =:= N-> 108 | {Value, Index + 1}; 109 | true-> 110 | {Item, Index + 1} 111 | end 112 | end, 1, List), 113 | NewList. 114 | 115 | str_normalize(String)-> 116 | New = replace(String,"_x000D_","\n"), 117 | replace(New,"_x000d_","\n"). 118 | 119 | token_str(String, TokenStr)-> 120 | Len = string:len(TokenStr), 121 | case string:str(String, TokenStr) of 122 | 0->[String]; 123 | 1-> 124 | LeftString = string:sub_string(String, Len + 1), 125 | token_str(LeftString, TokenStr); 126 | I-> 127 | FirstString = string:sub_string(String, 1, I - 1), 128 | LeftString = string:sub_string(String, I + Len), 129 | [FirstString | token_str(LeftString, TokenStr)] 130 | end. 131 | 132 | replace(String, TokenStr, NewString)-> 133 | SplitStrings = token_str(String, TokenStr), 134 | string:join(SplitStrings, NewString). 135 | 136 | %% @doc Convert (almost) any value to a list. 137 | -spec to_list(term()) -> string(). 138 | to_list(undefined) -> []; 139 | to_list(<<>>) -> []; 140 | to_list({rsc_list, L}) -> L; 141 | to_list(L) when is_list(L) -> L; 142 | to_list(A) when is_atom(A) -> atom_to_list(A); 143 | to_list(B) when is_binary(B) -> binary_to_list(B); 144 | to_list(I) when is_integer(I) -> integer_to_list(I); 145 | to_list(F) when is_float(F) -> digits(F). 146 | 147 | unpack(Float) -> 148 | <> = <>, 149 | {Sign, Exp, Frac}. 150 | 151 | 152 | frexp_int(F) -> 153 | case unpack(F) of 154 | {_Sign, 0, Frac} -> 155 | {Frac, ?MIN_EXP}; 156 | {_Sign, Exp, Frac} -> 157 | {Frac + (1 bsl 52), Exp - 53 - ?FLOAT_BIAS} 158 | end. 159 | 160 | scale(R, S, MPlus, MMinus, LowOk, HighOk, Float) -> 161 | Est = xlsx_util:int_ceil(math:log10(abs(Float)) - 1.0e-10), 162 | %% Note that the scheme implementation uses a 326 element look-up table 163 | %% for int_pow(10, N) where we do not. 164 | case Est >= 0 of 165 | true -> 166 | fixup(R, S * xlsx_util:int_pow(10, Est), MPlus, MMinus, Est, 167 | LowOk, HighOk); 168 | false -> 169 | Scale = xlsx_util:int_pow(10, -Est), 170 | fixup(R * Scale, S, MPlus * Scale, MMinus * Scale, Est, 171 | LowOk, HighOk) 172 | end. 173 | 174 | fixup(R, S, MPlus, MMinus, K, LowOk, HighOk) -> 175 | TooLow = case HighOk of 176 | true -> 177 | (R + MPlus) >= S; 178 | false -> 179 | (R + MPlus) > S 180 | end, 181 | case TooLow of 182 | true -> 183 | [(K + 1) | generate(R, S, MPlus, MMinus, LowOk, HighOk)]; 184 | false -> 185 | [K | generate(R * 10, S, MPlus * 10, MMinus * 10, LowOk, HighOk)] 186 | end. 187 | 188 | generate(R0, S, MPlus, MMinus, LowOk, HighOk) -> 189 | D = R0 div S, 190 | R = R0 rem S, 191 | TC1 = case LowOk of 192 | true -> 193 | R =< MMinus; 194 | false -> 195 | R < MMinus 196 | end, 197 | TC2 = case HighOk of 198 | true -> 199 | (R + MPlus) >= S; 200 | false -> 201 | (R + MPlus) > S 202 | end, 203 | case TC1 of 204 | false -> 205 | case TC2 of 206 | false -> 207 | [D | generate(R * 10, S, MPlus * 10, MMinus * 10, 208 | LowOk, HighOk)]; 209 | true -> 210 | [D + 1] 211 | end; 212 | true -> 213 | case TC2 of 214 | false -> 215 | [D]; 216 | true -> 217 | case R * 2 < S of 218 | true -> 219 | [D]; 220 | false -> 221 | [D + 1] 222 | end 223 | end 224 | end. 225 | 226 | digits1(Float, Exp, Frac) -> 227 | Round = ((Frac band 1) =:= 0), 228 | case Exp >= 0 of 229 | true -> 230 | BExp = 1 bsl Exp, 231 | case (Frac =/= ?BIG_POW) of 232 | true -> 233 | scale((Frac * BExp * 2), 2, BExp, BExp, 234 | Round, Round, Float); 235 | false -> 236 | scale((Frac * BExp * 4), 4, (BExp * 2), BExp, 237 | Round, Round, Float) 238 | end; 239 | false -> 240 | case (Exp =:= ?MIN_EXP) orelse (Frac =/= ?BIG_POW) of 241 | true -> 242 | scale((Frac * 2), 1 bsl (1 - Exp), 1, 1, 243 | Round, Round, Float); 244 | false -> 245 | scale((Frac * 4), 1 bsl (2 - Exp), 2, 1, 246 | Round, Round, Float) 247 | end 248 | end. 249 | 250 | 251 | 252 | digits(N) when is_integer(N) -> 253 | integer_to_list(N); 254 | digits(0.0) -> 255 | "0.0"; 256 | digits(Float) -> 257 | {Frac1, Exp1} = frexp_int(Float), 258 | [Place0 | Digits0] = digits1(Float, Exp1, Frac1), 259 | {Place, Digits} = transform_digits(Place0, Digits0), 260 | R = insert_decimal(Place, Digits), 261 | case Float < 0 of 262 | true -> 263 | [$- | R]; 264 | _ -> 265 | R 266 | end. 267 | 268 | transform_digits(Place, [0 | Rest]) -> 269 | transform_digits(Place, Rest); 270 | transform_digits(Place, Digits) -> 271 | {Place, [$0 + D || D <- Digits]}. 272 | 273 | 274 | 275 | insert_decimal(0, S) -> 276 | "0." ++ S; 277 | insert_decimal(Place, S) when Place > 0 -> 278 | L = length(S), 279 | case Place - L of 280 | 0 -> 281 | S ++ ".0"; 282 | N when N < 0 -> 283 | {S0, S1} = lists:split(L + N, S), 284 | S0 ++ "." ++ S1; 285 | N when N < 6 -> 286 | %% More places than digits 287 | S ++ lists:duplicate(N, $0) ++ ".0"; 288 | _ -> 289 | insert_decimal_exp(Place, S) 290 | end; 291 | insert_decimal(Place, S) when Place > -6 -> 292 | "0." ++ lists:duplicate(abs(Place), $0) ++ S; 293 | insert_decimal(Place, S) -> 294 | insert_decimal_exp(Place, S). 295 | 296 | insert_decimal_exp(Place, S) -> 297 | [C | S0] = S, 298 | S1 = case S0 of 299 | [] -> 300 | "0"; 301 | _ -> 302 | S0 303 | end, 304 | Exp = case Place < 0 of 305 | true -> 306 | "e-"; 307 | false -> 308 | "e+" 309 | end, 310 | [C] ++ "." ++ S1 ++ Exp ++ integer_to_list(abs(Place - 1)). 311 | 312 | 313 | 314 | %% @doc Escape a string so that it is valid within HTML/ XML. 315 | %% @spec escape(iolist()) -> binary() 316 | -spec escape(list()|binary()|{trans, list()}) -> binary() | undefined. 317 | escape({trans, Tr}) -> 318 | {trans, [{Lang, escape(V)} || {Lang,V} <- Tr]}; 319 | escape(undefined) -> 320 | undefined; 321 | escape(<<>>) -> 322 | <<>>; 323 | escape([]) -> 324 | <<>>; 325 | escape(L) when is_list(L) -> 326 | escape(list_to_binary(L)); 327 | escape(B) when is_binary(B) -> 328 | escape1(B, <<>>). 329 | 330 | escape1(<<>>, Acc) -> 331 | Acc; 332 | escape1(<<"€", T/binary>>, Acc) -> 333 | escape1(T, <>); 334 | escape1(<<$&, T/binary>>, Acc) -> 335 | escape1(T, <>); 336 | escape1(<<$<, T/binary>>, Acc) -> 337 | escape1(T, <>); 338 | escape1(<<$>, T/binary>>, Acc) -> 339 | escape1(T, <>); 340 | escape1(<<$", T/binary>>, Acc) -> 341 | escape1(T, <>); 342 | escape1(<<$', T/binary>>, Acc) -> 343 | escape1(T, <>); 344 | escape1(<>, Acc) -> 345 | escape1(T, <>). -------------------------------------------------------------------------------- /src/xlsx_writer.erl: -------------------------------------------------------------------------------- 1 | %%%------------------------------------------------------------------- 2 | %%% @author Adrianx Lau 3 | %%% @copyright (C) 2017, 4 | %%% @doc 5 | %%% 6 | %%% @end 7 | %%% Created : 22. 二月 2017 下午2:05 8 | %%%------------------------------------------------------------------- 9 | -module(xlsx_writer). 10 | -author("Adrianx Lau "). 11 | %%-record(xlsx, {tmp, files=[], sheets=[]}). 12 | -record(xlsx_write_context,{outfile = "",author="",files=[],sheets=[]}). 13 | -record(xlsx_write_sheet,{title,rows=[],dimension}). 14 | -record(xlsx_write_file,{name,content}). 15 | 16 | %% API 17 | -export([create/2,add_sheet/2,create_sheet/2,close/1]). 18 | 19 | create(Xlsx,Author)-> 20 | Handle = erlang:system_time(nano_seconds), 21 | put_context(Handle,#xlsx_write_context{outfile = Xlsx,author = Author}), 22 | Handle. 23 | 24 | add_sheet(XlsxHandle,SheetHandle)-> 25 | Context =#xlsx_write_context{sheets = Sheets}= get_context(XlsxHandle), 26 | NewContext = Context#xlsx_write_context{sheets = Sheets++ [SheetHandle]}, 27 | put_context(XlsxHandle,NewContext). 28 | 29 | create_sheet(Title,Rows)-> 30 | SheetHandle = erlang:system_time(nano_seconds), 31 | Dimension = normalize_dimension(Rows), 32 | SheetContext = #xlsx_write_sheet{title=Title,rows = add_rows([],Rows),dimension = Dimension}, 33 | put_sheet(SheetHandle,SheetContext), 34 | SheetHandle. 35 | 36 | add_rows(OldRows,NewRows)-> 37 | lists:foldl( 38 | fun([Index|Row],Acc)-> 39 | lists:keystore(Index,1,Acc,{Index,Row}) 40 | end,OldRows,NewRows). 41 | 42 | 43 | put_sheet(SheetHandle,SheetContext)-> 44 | put({xlsx_write_sheet,SheetHandle},SheetContext). 45 | 46 | get_sheet(SheetHandle)-> 47 | get({xlsx_write_sheet,SheetHandle}). 48 | 49 | normalize_dimension(Rows)-> 50 | {MaxColumn,MaxLine} = lists:foldl( 51 | fun([LineId|Row],{MaxCol,MaxLine})-> 52 | MC = if length(Row)> MaxCol-> length(Row); 53 | true-> MaxCol 54 | end, 55 | ML = if LineId> MaxLine-> LineId; 56 | true-> MaxLine 57 | end, 58 | {MC,ML} 59 | end,{0,0},Rows), 60 | ["A1:" , xlsx_util:get_field_string(MaxColumn ,MaxLine)]. 61 | 62 | put_context(XlsxHandle,Context)-> 63 | put({xlsx_write_context,XlsxHandle},Context). 64 | get_context(XlsxHandle)-> 65 | get({xlsx_write_context,XlsxHandle}). 66 | 67 | clear_sheet_context(SheetHandle)-> 68 | erase({xlsx_write_sheet,SheetHandle}). 69 | clear_context(XlsxHandle)-> 70 | #xlsx_write_context{sheets = Sheets}= get_context(XlsxHandle), 71 | lists:foreach(fun clear_sheet_context/1,Sheets), 72 | erase({xlsx_write_context,XlsxHandle}). 73 | 74 | close(XlsxHandle)-> 75 | process_save(XlsxHandle), 76 | clear_context(XlsxHandle). 77 | 78 | process_save(XlsxHandle)-> 79 | Context = #xlsx_write_context{outfile = File,sheets = Sheets} = get_context(XlsxHandle), 80 | Files = do_sheets(Sheets), 81 | Funs = 82 | [ 83 | fun do_doc_props/2, 84 | fun do_relation/2, 85 | fun do_style/2, 86 | fun do_workbook_relation/2, 87 | fun do_content_types/2, 88 | fun do_workbook/2 89 | ], 90 | 91 | AllFiles = lists:foldl(fun(F,Acc)-> F(Context,Acc) end, Files,Funs), 92 | ZipList = lists:map(fun(NF)-> {NF#xlsx_write_file.name, list_to_binary(NF#xlsx_write_file.content) } end,AllFiles), 93 | zip:create(File,ZipList). 94 | 95 | do_sheets(Sheets)-> 96 | lists:map( 97 | fun({Idx,SheetHandle}) -> 98 | I = integer_to_list(Idx), 99 | #xlsx_write_sheet{dimension = Dimension,rows = Rows} = get_sheet(SheetHandle), 100 | #xlsx_write_file{ 101 | name = "xl/worksheets/sheet" ++ I ++ ".xml", 102 | content = [ 103 | "" 104 | "" 105 | , Dimension 106 | ,"" , 107 | lists:map(fun({RIdx,Row})->encode_row(RIdx, Row) end, Rows), 108 | ""] 109 | } 110 | end, lists:zip(lists:seq(1, length(Sheets)), Sheets)). 111 | 112 | do_doc_props(#xlsx_write_context{author = Author}, Acc) -> 113 | {{Y,M,D},{H,Min,S}} = erlang:universaltime(), 114 | [ 115 | #xlsx_write_file{ 116 | name = "docProps/core.xml", 117 | content =[ 118 | "" 119 | "" 120 | " ",Author,"" 121 | " ",Author,"" 122 | " ",io_lib:format("~p-~2..0w-~2..0wT~2..0w:~2..0w:~2..0wZ",[Y,M,D,H,Min,S]),"" 123 | " 0" 124 | ""] 125 | }, 126 | #xlsx_write_file{ 127 | name = "docProps/app.xml", 128 | content = 129 | "" 130 | "" 131 | " 0" 132 | "" 133 | } | Acc 134 | ]. 135 | 136 | do_relation(_Context,Acc)-> 137 | [ 138 | #xlsx_write_file{ 139 | name = "_rels/.rels", 140 | content = "" 141 | "" 142 | " " 143 | " " 144 | " " 145 | "" 146 | } 147 | |Acc 148 | ]. 149 | 150 | do_style(_Context,Acc)-> 151 | [ 152 | #xlsx_write_file{ 153 | name = "xl/styles.xml", 154 | content = 155 | 156 | "" 157 | "" 158 | "" 159 | "" 160 | "" 161 | "" 162 | "" 163 | " " 164 | " " 165 | " " 166 | " " 167 | " " 168 | "" 169 | "" 170 | " " 171 | " " 172 | "" 173 | "" 174 | " " 175 | "" 176 | "" 177 | " " 178 | " " 179 | " " 181 | " " 182 | " " 183 | " " 184 | " " 185 | " " 186 | " " 187 | " " 188 | " " 189 | " " 190 | " " 191 | " " 192 | " " 193 | " " 194 | " " 195 | " " 196 | " " 197 | " " 198 | " " 199 | " " 200 | " " 201 | "" 202 | " " 203 | " " 204 | " " 205 | " " 206 | " " 207 | " " 208 | %% boolean 209 | " " 210 | %% string bold 211 | " " 212 | %% string italic 213 | " " 214 | 215 | %% string filled 216 | " " 217 | 218 | "" 219 | "" 220 | " " 221 | " " 222 | " " 223 | " " 224 | " " 225 | "" 226 | "" 227 | } 228 | |Acc 229 | ]. 230 | 231 | 232 | do_workbook_relation(#xlsx_write_context{sheets = Sheets},Acc)-> 233 | [ 234 | #xlsx_write_file{ 235 | name = "xl/_rels/workbook.xml.rels", 236 | content =[ 237 | "" 238 | "" 239 | "" 240 | , 241 | lists:map( 242 | fun(Id)-> 243 | I = integer_to_list(Id), 244 | [""] 245 | end,lists:seq(1,length(Sheets))), 246 | "", 247 | "" 248 | ] 249 | }|Acc 250 | ]. 251 | 252 | do_content_types(#xlsx_write_context{sheets = Sheets},Acc)-> 253 | [#xlsx_write_file{ 254 | name = "[Content_Types].xml", 255 | content = 256 | ["" 257 | "" 258 | "" 259 | "" 260 | "" 261 | "" 262 | "" 263 | "" 264 | , 265 | lists:map( 266 | fun(Id)-> 267 | I = integer_to_list(Id), 268 | [""] 269 | end,lists:seq(1,length(Sheets))) 270 | 271 | ,"" 272 | ""] 273 | }|Acc] 274 | . 275 | 276 | 277 | do_workbook(#xlsx_write_context{sheets = Sheets},Acc)-> 278 | [ 279 | #xlsx_write_file{ 280 | name = "xl/workbook.xml", 281 | content = 282 | ["" 283 | "" 284 | "" 285 | "" , 286 | lists:map( 287 | fun({Idx, SheetHandle}) -> 288 | I = integer_to_list(Idx), 289 | #xlsx_write_sheet{title = SheetName} = get_sheet(SheetHandle), 290 | [""] 291 | end, 292 | lists:zip(lists:seq(1, length(Sheets)), Sheets)) , 293 | ""] 294 | }|Acc]. 295 | 296 | encode_row(Idx, Row) -> 297 | I = integer_to_list(Idx), 298 | ["", 299 | [begin 300 | {Kind, Content, Style} = encode(Cell), 301 | ["", Content, "" 303 | ] 304 | end || {Col, Cell} <- lists:zip(lists:seq(0, length(Row)-1), Row)], 305 | ""]. 306 | 307 | %% Given 0-based column number return the Excel column name as list. 308 | column(N) -> 309 | column(N, []). 310 | column(N, Acc) when N < 26 -> 311 | [(N)+$A | Acc]; 312 | column(N, Acc) -> 313 | column(N div 26-1, [(N rem 26)+$A|Acc]). 314 | 315 | %% @doc Encode an Erlang term as an Excel cell. 316 | encode(true) -> 317 | {b, "1", 6}; 318 | encode(false) -> 319 | {b, "0", 6}; 320 | encode(I) when is_integer(I) -> 321 | {n, ["", integer_to_list(I), ""], 3}; 322 | encode(F) when is_float(F) -> 323 | {n, ["", float_to_list(F), ""], 4}; 324 | encode(_Dt = {{_,_,_},{_,_,_}}) -> 325 | {n, ["111"], 3}; 326 | %% @doc bold 327 | encode({b, Str}) -> 328 | {inlineStr, ["", xlsx_util:escape(xlsx_util:to_list(Str)), ""], 7}; 329 | %% @doc bold 330 | encode({i, Str}) -> 331 | {inlineStr, ["", xlsx_util:escape(xlsx_util:to_list(Str)), ""], 8}; 332 | encode({f, Str}) -> 333 | {inlineStr, ["", xlsx_util:escape(xlsx_util:to_list(Str)), ""], 9}; 334 | encode(Str) -> 335 | {inlineStr, ["", xlsx_util:escape(xlsx_util:to_list(Str)), ""], 5}. 336 | -------------------------------------------------------------------------------- /src/xlsxio.app.src: -------------------------------------------------------------------------------- 1 | {application, xlsxio, 2 | [ 3 | {description, ""}, 4 | {vsn, "1"}, 5 | {registered, []}, 6 | {applications, [ 7 | kernel, 8 | stdlib 9 | ]}, 10 | {mod, { xlsxio, []}}, 11 | {env, []} 12 | ]}. 13 | -------------------------------------------------------------------------------- /src/xlsxio.erl: -------------------------------------------------------------------------------- 1 | -module(xlsxio). 2 | 3 | -behaviour(application). 4 | 5 | %% Application callbacks 6 | -export([start/2, stop/1]). 7 | -export([start/0]). 8 | -export([test/0]). 9 | -export([test2/0]). 10 | %% =================================================================== 11 | %% Application callbacks 12 | %% =================================================================== 13 | start(_StartType, _StartArgs) -> 14 | xlsxio_sup:start_link(). 15 | 16 | stop(_State) -> 17 | ok. 18 | 19 | start()-> 20 | application:start(?MODULE). 21 | 22 | test2()-> 23 | XlsxFile = "xlsx/t2.xlsx", 24 | XlsxHandle = xlsx_writer:create(XlsxFile,unicode:characters_to_binary("刘金鑫")), 25 | SheetHandle = xlsx_writer:create_sheet("Hello",[[1,1,unicode:characters_to_binary("刘某人"),2],[2,2.6,""]]), 26 | SheetHandle2 = xlsx_writer:create_sheet("Hello2",[[2,1,1,2],[3,2,2],[10,abc]]), 27 | xlsx_writer:add_sheet(XlsxHandle,SheetHandle), 28 | xlsx_writer:add_sheet(XlsxHandle,SheetHandle2), 29 | xlsx_writer:close(XlsxHandle). 30 | 31 | 32 | test()-> 33 | XlsxFile = "xlsx/t.xlsx", 34 | RowHandler = 35 | fun(SheetName, [1 | Row],Context) -> 36 | io:format("~n~ts=====>~p | ", [SheetName, 1]), 37 | lists:foreach(fun(R)-> io:format("\t~ts",[R]) end,Row), 38 | {next_row,Context}; 39 | (SheetName, [Line | Row],Context) -> 40 | io:format("~n~ts=====>~p | ", [SheetName, Line]), 41 | lists:foreach(fun(R)-> io:format("\t~ts",[R]) end,Row), 42 | {next_row,Context} 43 | end, 44 | InputContext = input, 45 | case xlsx_reader:read(XlsxFile,InputContext,RowHandler) of 46 | {error,Reason}-> io:format("read error:~p~n",[Reason]); 47 | ok-> io:format("~n") 48 | end. -------------------------------------------------------------------------------- /src/xlsxio_sup.erl: -------------------------------------------------------------------------------- 1 | -module(xlsxio_sup). 2 | 3 | -behaviour(supervisor). 4 | 5 | %% API 6 | -export([start_link/0]). 7 | 8 | %% Supervisor callbacks 9 | -export([init/1]). 10 | 11 | %% Helper macro for declaring children of supervisor 12 | -define(CHILD(I, Type), {I, {I, start_link, []}, permanent, 5000, Type, [I]}). 13 | 14 | %% =================================================================== 15 | %% API functions 16 | %% =================================================================== 17 | 18 | start_link() -> 19 | supervisor:start_link({local, ?MODULE}, ?MODULE, []). 20 | 21 | %% =================================================================== 22 | %% Supervisor callbacks 23 | %% =================================================================== 24 | 25 | init([]) -> 26 | {ok, { {one_for_one, 5, 10}, []} }. 27 | 28 | -------------------------------------------------------------------------------- /xlsx/t.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adrianx77/Xlsx-Reader-Writer/7485fe1f506465d44b6b33e2189fb351c55d6b38/xlsx/t.xlsx --------------------------------------------------------------------------------