您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 
 
 

108 行
3.6 KiB

  1. # Copyright (c) 2012 Web Notes Technologies Pvt Ltd (http://erpnext.com)
  2. #
  3. # MIT License (MIT)
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a
  6. # copy of this software and associated documentation files (the "Software"),
  7. # to deal in the Software without restriction, including without limitation
  8. # the rights to use, copy, modify, merge, publish, distribute, sublicense,
  9. # and/or sell copies of the Software, and to permit persons to whom the
  10. # Software is furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in
  13. # all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  16. # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
  17. # PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  18. # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  19. # CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
  20. # OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  21. #
  22. from __future__ import unicode_literals
  23. import webnotes
  24. import json
  25. import csv, cStringIO
  26. from webnotes.utils import encode, cstr
  27. def read_csv_content_from_uploaded_file(ignore_encoding=False):
  28. from webnotes.utils.file_manager import get_uploaded_content
  29. fname, fcontent = get_uploaded_content()
  30. return read_csv_content(fcontent, ignore_encoding)
  31. def read_csv_content_from_attached_file(doc):
  32. fileid = webnotes.conn.get_value("File Data", {"attached_to_doctype": doc.doctype,
  33. "attached_to_name":doc.name}, "name")
  34. if not fileid:
  35. msgprint("File not attached!")
  36. raise Exception
  37. try:
  38. from webnotes.utils.file_manager import get_file
  39. fname, fcontent = get_file(fileid)
  40. return read_csv_content(fcontent, webnotes.form_dict.get('ignore_encoding_errors'))
  41. except Exception, e:
  42. webnotes.msgprint("""Unable to open attached file. Please try again.""")
  43. raise Exception
  44. def read_csv_content(fcontent, ignore_encoding=False):
  45. import csv
  46. from webnotes.utils import cstr
  47. rows = []
  48. try:
  49. reader = csv.reader(fcontent.splitlines())
  50. # decode everything
  51. csvrows = [[val for val in row] for row in reader]
  52. for row in csvrows:
  53. newrow = []
  54. for val in row:
  55. if ignore_encoding:
  56. newrow.append(cstr(val.strip()))
  57. else:
  58. try:
  59. newrow.append(unicode(val.strip(), 'utf-8'))
  60. except UnicodeDecodeError, e:
  61. raise Exception, """Some character(s) in row #%s, column #%s are
  62. not readable by utf-8. Ignoring them. If you are importing a non
  63. english language, please make sure your file is saved in the 'utf-8'
  64. encoding.""" % (csvrows.index(row)+1, row.index(val)+1)
  65. rows.append(newrow)
  66. return rows
  67. except Exception, e:
  68. webnotes.msgprint("Not a valid Comma Separated Value (CSV File)")
  69. raise e
  70. @webnotes.whitelist()
  71. def send_csv_to_client(args):
  72. if isinstance(args, basestring):
  73. args = json.loads(args)
  74. args = webnotes._dict(args)
  75. webnotes.response["result"] = cstr(to_csv(args.data))
  76. webnotes.response["doctype"] = args.filename
  77. webnotes.response["type"] = "csv"
  78. def to_csv(data):
  79. writer = UnicodeWriter()
  80. for row in data:
  81. writer.writerow(row)
  82. return writer.getvalue()
  83. class UnicodeWriter:
  84. def __init__(self, encoding="utf-8"):
  85. self.encoding = encoding
  86. self.queue = cStringIO.StringIO()
  87. self.writer = csv.writer(self.queue, quoting=csv.QUOTE_NONNUMERIC)
  88. def writerow(self, row):
  89. row = encode(row, self.encoding)
  90. self.writer.writerow(row)
  91. def getvalue(self):
  92. return self.queue.getvalue()