C# данные импорта Excel из CSV в Excel

Щелкните правой кнопкой по файлу проекта, выберите Свойства.

В окне, которое открывается, перейдите к вкладке Resources, и если это имеет просто синюю ссылку посреди вкладки, нажмите его, для создания нового ресурса.

enter image description here

Затем от панели инструментов выше вкладки, выберите, чтобы добавить новый текстовый файл, дать ему имя, это будет добавлено к Вашему проекту и открыто.

, Если Вы добираетесь настолько далеко, затем в Вашем коде, можно ввести в Ресурсах. TheNameYouGaveTheTextFileHere и Вы можете получить доступ к своему содержанию. Обратите внимание в первый раз использование класса Ресурсов в классе необходимо добавить, директива использования (поразите Ctrl +. после ввода Ресурсов, чтобы заставить меню заставлять VS делать это для Вас).

, Если что-то было неясно о вышеупомянутом описании, оставьте комментарий, и я отредактирую его, пока это не будет завершено или имеет смысл :)

8
задан akif 19 October 2009 в 08:09
поделиться

5 ответов

Вы можете открыть Excel, начать запись макроса, сделать что хотите, а затем посмотреть, что записал макрос. Это должно сказать вам, какие объекты использовать и как их использовать.

7
ответ дан 5 December 2019 в 07:35
поделиться

Я думаю, вы слишком много усложняете. Excel автоматически разбивает данные на столбцы через запятую, если это файл CSV. Поэтому все, что вам нужно сделать, это убедиться, что ваше расширение - CSV.

Я просто попытался быстро открыть файл в Excel, и он отлично работает. Так что вам действительно нужно просто вызвать Workbook.Open () с файлом с расширением CSV.

8
ответ дан 5 December 2019 в 07:35
поделиться

I beleive there are two parts, one is the split operation for the csv that the other responder has already picked up on, which I don't think is essential but I'll include anyways. And the big one is the writing to the excel file, which I was able to get working, but under specific circumstances and it was a pain to accomplish.

CSV is pretty simple, you can do a string.split on a comma seperator if you want. However, this method is horribly broken, albeit I'll admit I've used it myself, mainly because I also have control over the source data, and know that no quotes or escape characters will ever appear. I've included a link to an article on proper csv parsing, however, I have never tested the source or fully audited the code myself. I have used other code by the same author with success. http://www.boyet.com/articles/csvparser.html

The second part is alot more complex, and was a huge pain for me. The approach I took was to use the jet driver to treat the excel file like a database, and then run SQL queries against it. There are a few limitations, which may cause this to not fit you're goal. I was looking to use prebuilt excel file templates to basically display data and some preset functions and graphs. To accomplish this I have several tabs of report data, and one tab which is raw_data. My program writes to the raw_data tab, and all the other tabs calculations point to cells in this table. I'll go into some of the reasoning for this behavior after the code:

First off, the imports (not all may be required, this is pulled from a larger class file and I didn't properly comment what was for what):

using System.IO;
using System.Diagnostics;
using System.Data.Common;
using System.Globalization;

Next we need to define the connection string, my class already has a FileInfo reference at this point to the file I want to use, so that's what I pass on. It's possible to search on google what all the parameters are for, but basicaly use the Jet Driver (should be available on ANY windows install) to open an excel file like you're referring to a database.

string connectString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={filename};Extended Properties=""Excel 8.0;HDR=YES;IMEX=0""";
connectString = connectString.Replace("{filename}", fi.FullName);

Now let's open up the connection to the DB, and be ready to run commands on the DB:

DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");

using (DbConnection connection = factory.CreateConnection())
{
  connection.ConnectionString = connectString;
  using (DbCommand command = connection.CreateCommand())
  {
    connection.Open();

Next we need the actual logic for DB insertion. So basically throw queries into a loop or whatever you're logic is, and insert the data row-by-row.

string query = "INSERT INTO [raw_aaa$] (correlationid, ipaddr, somenum) VALUES (\"abcdef", \"1.1.1.1", 10)";
command.CommandText = query;
command.ExecuteNonQuery();

Now here's the really annoying part, the excel driver tries to detect you're column type before insert, so even if you pass a proper integer value, if excel thinks the column type is text, it will insert all you're numbers as text, and it's very hard to get this treated like a number. As such, excel must already have the column type as the number. In order to accomplish this, for my template file I fill in the first 10 rows with dummy data, so that when you load the file in the jet driver, it can detect the proper types and use them. Then all my forumals that point at my csv table will operate properly since the values are of the right type. This may work for you if you're goals are similar to mine, and to use templates that already point to this data (just start at row 10 instead of row 2).

Because of this, my raw_aaa tab in excel might look something like this: correlationid ipaddr somenum abcdef 1.1.1.1 5 abcdef 1.1.1.1 5 abcdef 1.1.1.1 5 abcdef 1.1.1.1 5 abcdef 1.1.1.1 5 abcdef 1.1.1.1 5 abcdef 1.1.1.1 5 abcdef 1.1.1.1 5

Обратите внимание, что строка 1 - это имена столбцов, на которые я ссылался в своих запросах sql. Я думаю, вы можете обойтись и без этого, но это потребует дополнительных исследований. Если эти данные уже есть в файле excel, столбец somenum будет обнаружен как число, и любые вставленные данные будут правильно обрабатываться как таковые.

Замечание Antoher, которое делает это раздражающим, драйвер Jet Driver только 32-разрядный, поэтому в моем случае, когда у меня была явная 64-битная программа, я не смог выполнить ее напрямую. Итак, у меня был мерзкий прием: запись в файл, а затем запуск программы, которая вставляла данные из файла в мой шаблон Excel.

В общем, я думаю, что решение довольно неприятное, но пока что нет. нашел лучший способ сделать это, к сожалению. Удачи!

4
ответ дан 5 December 2019 в 07:35
поделиться

Что ж, импорт из CSV не должен вызывать больших проблем. Я думаю, что самый простой метод - использовать строковые операции. Вы можете создать довольно хороший синтаксический анализатор, используя простую команду Split () и получая данные в виде массивов.

-1
ответ дан 5 December 2019 в 07:35
поделиться
1
ответ дан 5 December 2019 в 07:35
поделиться
Другие вопросы по тегам:

Похожие вопросы: