private void FillListBox() { lblFolder.Text = "Files on folder: " + Path.GetDirectoryName(openFileDialog1.FileName); DirectoryInfo di = new DirectoryInfo(Path.GetDirectoryName(openFileDialog1.FileName)); FileInfo[] Fi = di.GetFiles("*.xls"); FilesListBox.Items.Clear(); TImageInfo[] Files = new TImageInfo[Fi.Length]; for (int k = 0; k < Fi.Length; k++) { FileInfo f = Fi[k]; bool HasCrop = false; bool HasARGB = false; XlsFile x1 = new XlsFile(); bool HasImages = false; try { x1.Open(f.FullName); for (int sheet = 1; sheet <= x1.SheetCount; sheet++) { x1.ActiveSheet = sheet; for (int i = x1.ImageCount; i > 0; i--) { HasImages = true; TImageProperties ip = x1.GetImageProperties(i); if (!HasCrop) { HasCrop = GetHasCrop(ip); } TXlsImgType imgType = TXlsImgType.Unknown; using (MemoryStream ms = new MemoryStream()) { x1.GetImage(i, ref imgType, ms); FlexCel.Pdf.TPngInformation PngInfo = FlexCel.Pdf.TPdfPng.GetPngInfo(ms); if (PngInfo != null) { HasARGB = PngInfo.ColorType == 6; } } } } } catch (Exception) { Files[k] = new TImageInfo(f, false, false, false, false); continue; } Files[k] = new TImageInfo(f, true, HasCrop, HasImages, HasARGB); } FilesListBox.Items.AddRange(Files); }
private void OpenFile(string FileName) { ImageDataTable.Rows.Clear(); try { XlsFile Xls = new XlsFile(true); CurrentFilename = FileName; Xls.Open(FileName); for (int sheet = 1; sheet <= Xls.SheetCount; sheet++) { Xls.ActiveSheet = sheet; for (int i = Xls.ImageCount; i > 0; i--) { TXlsImgType ImageType = TXlsImgType.Unknown; byte[] ImgBytes = Xls.GetImage(i, ref ImageType); TImageProperties ImgProps = Xls.GetImageProperties(i); object[] ImgData = new object[ImageDataTable.Columns.Count]; ImgData[0] = Xls.SheetName; ImgData[1] = i; ImgData[4] = ImageType.ToString(); ImgData[7] = Xls.GetImageName(i); ImgData[8] = ImgBytes; ImgData[9] = GetHasCrop(ImgProps); using (MemoryStream ms = new MemoryStream(ImgBytes)) { FlexCel.Pdf.TPngInformation PngInfo = FlexCel.Pdf.TPdfPng.GetPngInfo(ms); if (PngInfo != null) { ImgData[2] = PngInfo.Width; ImgData[3] = PngInfo.Height; string s = String.Empty; int bpp = 0; if ((PngInfo.ColorType & 4) != 0) { s += "ALPHA-"; bpp = 1; } if ((PngInfo.ColorType & 2) == 0) { s += "Grayscale -" + (1 << PngInfo.BitDepth).ToString() + " shades. "; bpp = 1; } else { if ((PngInfo.ColorType & 1) == 0) { bpp += 3; s += "RGB - " + (PngInfo.BitDepth * (bpp)).ToString() + "bpp. "; } else { s += "Indexed - " + (1 << PngInfo.BitDepth).ToString() + " colors. "; bpp = 1; } } ImgData[5] = s; ImgData[6] = (Math.Round(PngInfo.Width * PngInfo.Height * PngInfo.BitDepth * bpp / 8f / 1024f)).ToString() + " kb."; } else { ms.Position = 0; try { using (Image Img = Image.FromStream(ms)) { Bitmap Bmp = Img as Bitmap; if (Bmp != null) { ImgData[5] = Bmp.PixelFormat.ToString() + "bpp"; } ImgData[2] = Img.Width; ImgData[3] = Img.Height; } } catch (Exception) { ImgData[2] = -1; ImgData[3] = -1; ImgData[5] = null; ImgData[8] = null; } } } ImageDataTable.Rows.Add(ImgData); } } } catch (Exception ex) { MessageBox.Show(ex.Message, "Error"); dataGrid.CaptionText = "No file selected"; CurrentFilename = null; return; } dataGrid.CaptionText = "Selected file: " + FileName; CurrentRowChanged(GetCurrencyManager, null); }
/// <summary> /// Читает данные с текущего листа XLS-файла. /// </summary> /// <param name="xlsFile">XSL-файл.</param> /// <returns>Таблица с прочитанными данными.</returns> private static DataTable ReadDataTable(XlsFile xlsFile) { // установить имя таблицы DataTable table = new DataTable(xlsFile.GetSheetName(xlsFile.ActiveSheet)); // первая строка - названия столбцов // вторая строка - типы столбцов if (xlsFile.RowCount < 2) throw new CoreInvalidOperationException(Resources.ResourceManager.GetString("InvalidFileFormatException")); // прочитать имена столбцов для таблицы for (int col = 0; col < xlsFile.ColCount; col++) { if (xlsFile.GetCellValue(1, col + 1) == null) break; // прочитать тип столбца Type columnType = Type.GetType(xlsFile.GetCellValue(2, col + 1).ToString(), false); if (columnType == null) throw new CoreInvalidOperationException(Resources.ResourceManager.GetString("InvalidFileFormatException")); table.Columns.Add(xlsFile.GetCellValue(1, col + 1).ToString(), columnType); } // прочитать данные int rowFrom = 2; /* XlsFile тупо обрабатывает * вложенные картинки. Поместить картинку в определённую клетку можно, * а вот взять её из клетки нельзя. Взять картинку можно только из массива * рисунков Excel, начинающегося почему то с 2 (хотя в доке написано ч 1!). * Будем надеяться, что они там в правильном порядке лежат. */ int imageCount = 2; for (int row = rowFrom; row < xlsFile.RowCount; ++row) { // Т.к. XlsFile очень часто врёт по поводу количества строк в файле, // то мы подстраховываемся таким образом. Считаем, что данные кончились, // если колонка 'A' в строке пустая if (xlsFile.GetCellValue(row + 1, 1) == null) break; object[] values = new object[table.Columns.Count]; for(int col = 0; col < table.Columns.Count; ++col) { if(table.Columns[col].DataType == typeof( byte[] )) { TXlsImgType imageType = TXlsImgType.Unknown; values[col] = ConvertValue( xlsFile.GetImage( imageCount++, ref imageType ), table.Columns[col].DataType ); } else { values[col] = ConvertValue( xlsFile.GetCellValue( row + 1, col + 1 ), table.Columns[col].DataType ); } } table.Rows.Add(values); } return table; }