Изменить входящий тип Excel на строку - PullRequest
0 голосов
/ 06 июня 2018

Я читаю данные из книги Excel, используя openfiledialog

String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + openFileDialog1.FileName + "; Extended Properties=\"Excel 12.0 XML; HDR=YES; IMEX = 1\"; ";

книга полностью динамическая, может быть 5 или даже 50 столбцов, я отправляю входящие данные в datagridview, используя это

OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]", con);
con.Open();

OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
DataTable data = new DataTable();
sda.Fill(data);
for (int i = 0; i <= data.Rows.Count; i++)
{
    for (int z = 0; z < data.Columns.Count; z++)
    {
        DataGridViewComboBoxCell cb = new DataGridViewComboBoxCell();
        cb.DropDownWidth = 250;
        fillComboCell(cb);
        cb.Sorted = true;
        dataGridView1.Rows[0].Cells[z] = cb;                          
        dataGridView1.Rows[1].Cells[z].Value = data.Columns[z];//Shows header of Dataset
        //Makes first line bold
        System.Windows.Forms.DataGridViewCellStyle boldStyle = new System.Windows.Forms.DataGridViewCellStyle();
        boldStyle.Font = new System.Drawing.Font("Calibri", 12, System.Drawing.FontStyle.Bold);
        dataGridView1.Rows[1].DefaultCellStyle = boldStyle;
        dataGridView1.Rows[i + 2].Cells[z].Value = data.Rows[i][z];
     }
}
con.Close();
con.Dispose();

Нет проблем с чтением данных с помощью этого кода (я не разделял весь свой код, так как он длинный, поэтому он может не работать при его копировании).

МойПроблема в том, что в моей книге есть столбец, который отформатирован как "пользовательский": чч: мм: сс, если быть точным.Значения, которые я вижу, когда открываю книгу, выглядят так: 09:52:17, но когда я считываю данные в мое представление данных, оно меняется на это 30/12/1899 09:52:17.

Вот мой вопрос: они мне не нужнызначения с пользовательскими типами.Все, что я хочу сделать с этой программой, это преобразовать это содержимое Excel в файл XML.Проблема в том, что я обрабатываю эту ячейку как строковую ячейку, как и другие ячейки, и когда я это делаю, происходит сбой моей программы.И из-за динамических файлов Excel я не могу сказать, какие столбцы будут datetime или int или что-то еще.Я проверил строки подключения Excel, но там ничего не нашел, но думаю, что это связано со строкой подключения.Может ли кто-нибудь помочь мне прочитать содержимое всей книги в виде только строки без изменения каких-либо значений внутри нее?

1 Ответ

0 голосов
/ 06 июня 2018

Я только что понял это;

 for (int i = 2; i <= xlWorksheet.UsedRange.Rows.Count; i++)
                {
                    if (Playlist_Path_col != 0) { Playlist_Path = xlRange.Cells[i, Playlist_Path_col].Text; }
                    if (Playlist_Audio_Path_col != 0) { Playlist_Audio_Path = xlRange.Cells[i, Playlist_Audio_Path_col].Text; }
                    if (Playlist_Duration_col != 0) { Playlist_Duration = xlRange.Cells[i, Playlist_Duration_col].Text; }
                    if (Playlist_Auto_Start_col != 0) { Playlist_Auto_Start = xlRange.Cells[i, Playlist_Auto_Start_col].Text; }
                    if (Playlist_Date_col != 0) { Playlist_Date = xlRange.Cells[i, Playlist_Date_col].Text; }

                    if (Video_Path_col != 0) { Video_Path = xlRange.Cells[i, Video_Path_col].Text; }
                    if (Video_Audio_Path_col != 0) { Video_Audio_Path = xlRange.Cells[i, Video_Audio_Path_col].Text; }
                    if (Video_NameExt_col != 0) { Video_NameExt = xlRange.Cells[i, Video_NameExt_col].Text; }
                    if (Video_Name_col != 0) { Video_Name = xlRange.Cells[i, Video_Name_col].Text; }
                    if (Video_Note_col != 0) { Video_Note = xlRange.Cells[i, Video_Note_col].Text; }
                    if (Video_Category_col != 0) { Video_Category = xlRange.Cells[i, Video_Category_col].Text; }
                    if (Video_URL_col != 0) { Video_URL = xlRange.Cells[i, Video_URL_col].Text; }

                    if (Video_In_Time_col != 0) { Video_In_Time = xlRange.Cells[i, Video_In_Time_col].Text; }
                    if (Video_INOUT_Duration_col != 0) { Video_INOUT_Duration = xlRange.Cells[i, Video_INOUT_Duration_col].Text; }
                    if (Video_Width_col != 0) { Video_Width = xlRange.Cells[i, Video_Width_col].Text; }
                    if (Video_Height_col != 0) { Video_Height = xlRange.Cells[i, Video_Height_col].Text; }
                    if (Video_Rate_col != 0) { Video_Rate = xlRange.Cells[i, Video_Rate_col].Text; }
                    if (Video_Colorspace_col != 0) { Video_Colorspace = xlRange.Cells[i, Video_Colorspace_col].Text; }
                    if (Video_Aspect_Ratio_col != 0) { Video_Aspect_Ratio = xlRange.Cells[i, Video_Aspect_Ratio_col].Text; }
                    if (Video_Interlace_col != 0) { Video_Interlace = xlRange.Cells[i, Video_Interlace_col].Text; }

                    if (Audio_Channel_col != 0) { Audio_Channel = xlRange.Cells[i, Audio_Channel_col].Text; }
                    if (Audio_Channel_Bit_col != 0) { Audio_Channel_Bit = xlRange.Cells[i, Audio_Channel_Bit_col].Text; }
                    if (Audio_Bit_Rate_col != 0) { Audio_Bit_Rate = xlRange.Cells[i, Audio_Bit_Rate_col].Text; }

                    if (LiveSource_Path_col != 0) { LiveSource_Path = xlRange.Cells[i, LiveSource_Path_col].Text; }
                    if (LiveSource_Audio_Path_col != 0) { LiveSource_Audio_Path = xlRange.Cells[i, LiveSource_Audio_Path_col].Text; }
                    if (LiveSource_Name_col != 0) { LiveSource_Name = xlRange.Cells[i, LiveSource_Name_col].Text; }
                    if (LiveSource_Note_col != 0) { LiveSource_Note = xlRange.Cells[i, LiveSource_Note_col].Text; }
                    if (LiveSource_Category_col != 0) { LiveSource_Category = xlRange.Cells[i, LiveSource_Category_col].Text; }
                    if (LiveSource_URL_col != 0) { LiveSource_URL = xlRange.Cells[i, LiveSource_URL_col].Text; }

                    if (LiveSource_IN_Time_col != 0) { LiveSource_IN_Time = xlRange.Cells[i, LiveSource_IN_Time_col].Text; }
                    if (LiveSource_OUT_Time_col != 0) { LiveSource_OUT_Time = xlRange.Cells[i, LiveSource_OUT_Time_col].Text; }
                    if (LiveSource_INOUT_Duration_col != 0) { LiveSource_INOUT_Duration = xlRange.Cells[i, LiveSource_INOUT_Duration_col].Text; }

                    if (LiveSource_Width_col != 0) { LiveSource_Width = xlRange.Cells[i, LiveSource_Width_col].Text; }
                    if (LiveSource_Height_col != 0) { LiveSource_Height = xlRange.Cells[i, LiveSource_Height_col].Text; }
                    if (LiveSource_Rate_col != 0) { LiveSource_Rate = xlRange.Cells[i, LiveSource_Rate_col].Text; }
                    if (LiveSource_Colorspace_col != 0) { LiveSource_Colorspace = xlRange.Cells[i, LiveSource_Colorspace_col].Text; }
                    if (LiveSource_Aspect_Ratio_col != 0) { LiveSource_Aspect_Ratio = xlRange.Cells[i, LiveSource_Aspect_Ratio_col].Text; }
                    if (LiveSource_Interlace_col != 0) { LiveSource_Interlace = xlRange.Cells[i, LiveSource_Interlace_col].Text; }

                    if (LiveSource_Channel_col != 0) { LiveSource_Channel = xlRange.Cells[i, LiveSource_Channel_col].Text; }
                    if (LiveSource_Channel_Bit_col != 0) { LiveSource_Channel_Bit = xlRange.Cells[i, LiveSource_Channel_Bit_col].Text; }
                    if (LiveSource_Bit_Rate_col != 0) { LiveSource_Bit_Rate = xlRange.Cells[i, LiveSource_Bit_Rate_col].Text; }

Я использовал xlRange.Cells [i, LiveSource_Bit_Rate_col] .Value2;так что эта команда давала мне значение ячейки, но она также давала мне значение с ее форматом ... поэтому я снова искал и нашел .Text вместо .Value2, и он работал очень хорошо ... и при заполнении моего представления данных яиспользовал это

 string[] format = new string[] { "dd/MM/yyyy HH:mm:ss" };
                            DateTime datetime;
                            if (DateTime.TryParseExact(data.Rows[i][z].ToString(), format, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.NoCurrentDateDefault, out datetime))
                                dataGridView1.Rows[i + 2].Cells[z].Value = datetime.ToString("hh:MM:ss");
                            else
                                dataGridView1.Rows[i + 2].Cells[z].Value = data.Rows[i][z];

Это немного сложно, но работает очень хорошо в настоящее время ..

...