简体   繁体   English

将DataTable作为文件保存到数据库

[英]Save DataTable to database as a file

I have a DataTable, dt that I want to email to a user as a CSV file. 我有一个DataTable, dt我想通过CSV文件通过电子邮件发送给用户。 The existing emailing workflow involves adding the file to an attachments table and then the emailing function will pull the file from there. 现有的电子邮件工作流程涉及将文件添加到attachments表,然后电子邮件功能将从那里将文件拉出。 For now, I'm bypassing teh email part and downloading the file directly using the ID and a function that works for all the other files in the table (which includes csv and xls). 现在,我将绕过电子邮件部分,直接使用ID和适用于表中所有其他文件(包括csv和xls)的功能直接下载文件。 The problem is that everything I've tried for adding the DataTable as a file to this table will be downloaded as random Unicode characters. 问题是,我尝试将DataTable作为文件添加到此表的所有内容都将作为随机Unicode字符下载。

What I've tried: 我尝试过的

  • Convert DataTable to CSV string and use System.Text.Encoding.ASCII.GetBytes(attachmentCSV) to make a byte[] 将DataTable转换为CSV字符串,然后使用System.Text.Encoding.ASCII.GetBytes(attachmentCSV)制作一个byte[]
  • Create a MemoryStream as explained here 按照此处的说明创建MemoryStream
  • Combinations of the previous 2 前2个的组合

I'm not finding anything else helpful through my searching, so I'm at a loss at what to try next. 通过搜索我没有发现其他有用的信息,因此我不知所措。 How can I take a DataTable and save it into a SQL table as a file (csv, xls, any spreadsheet format that Excel will open)? 如何获取数据表并将其保存为SQL表文件(CSV,XLS,Excel将打开的任何电子表格格式)? Ideally, I'd like a way that avoids saving the file to disk first. 理想情况下,我想要一种避免首先将文件保存到磁盘的方法。

This problem lies in the software being used to open the file, LibreOffice. 此问题在于用于打开文件的软件LibreOffice。 The character set was being set to UTF-16 instead of UTF-8. 字符集被设置为UTF-16而不是UTF-8。 Changing the set appears to fix the problem. 更改设置似乎可以解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM