apache-poi
Начало работы с NPOI
Поиск…
Вступление
Это версия .NET проекта POI Java. он позволяет читать / записывать файлы xls, doc, ppt без установки Microsoft Office. Подробная информация о документации доступна здесь: https://github.com/tonyqus/npoi
Установка NPOI
Лучший способ включить всю библиотеку, связанную с NPOI, - это менеджер пакетов NUGet. Найдите NPOI в окне менеджера пакетов NUGet.
Как только он будет успешно установлен, вся необходимая библиотека появится в справочном разделе вашего текущего проекта
Затем включите NPOI в свой файл, как это
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.UserModel
Создать файл Excel
MemoryStream excelMS = GetExcelFile();
//Using Resposne Stream to Make File Available for User to Download;
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", @"Excel_" + DateTime.Now.ToString("yyyy-dd-M-HH-mm") + ".xlsx"));
Response.BinaryWrite(excelMS.ToArray());
Response.End();
будьте осторожны при использовании MIME-типа. вы будете выбирать разные типы MIME для разных форматов файлов. Для расширения EX xltm это будет «application / vnd.ms-excel.template.macroEnabled.12»; Расширение xlxs будет «application / vnd.openxmlformats-officedocument.spreadsheetml.sheet»; Различные типы MIME, поддерживаемые MS, находятся по этой ссылке .
public MemoryStream GetExcelFile()
{
//Excel File Stream
MemoryStream ms = null;
// create workbook
XSSFWorkbook workbook = new XSSFWorkbook();
// the table named mySheet
//Assigning New Sheet Name /
XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet("WorkSheet");
// Assuming FreezePaneRow = 10, FreezePaneColumn = 11 in the config file
int freezeRow = Convert.ToInt32(ConfigurationManager.AppSettings["FreezePaneRow"]);
int freezeCol = Convert.ToInt32(ConfigurationManager.AppSettings["FreezePaneCol"]);
try
{
// Freeze Created Excel Sheet Row;
sheet.CreateFreezePane(freezeCol, freezeRow, freezeCol, freezeRow);
//Freezing only the Header Row;
sheet.CreateFreezePane(0, 1);
using (ms = new MemoryStream())
{
logger.Info("Using Memory Stream to Create New WorkBook");
workbook.Write(ms); // Write to memory stream for download through browser
}
}
catch (Exception Ex)
{ ... }
return ms;
}
Чтение файла Excel
Существует различный подход к чтению файла excel. Я приведу пример с параметром пути к файлу. Вы можете получить различный способ прочитать файл на этом посту.
public void ReadExcel(string path)
{
// Write data in workbook from xls document.
XSSFWorkbook workbook = new XSSFWorkbook(path);
// Read the current table data
XSSFSheet sheet = (XSSFSheet)workbook.GetSheetAt(0);
// Read the current row data
XSSFRow headerRow = (XSSFRow)sheet.GetRow(0);
// LastCellNum is the number of cells of current rows
int cellCount = headerRow.LastCellNum;
DataTable dt = new DataTable();
bool isBlanKRow = false;
try
{
if (dt.Rows.Count == 0)
{
//Reading First Row as Header for Excel Sheet;
try
{
for (int j = headerRow.FirstCellNum; j < cellCount; j++)
{
// get data as the column header of DataTable
DataColumn column = new DataColumn(headerRow.GetCell(j).StringCellValue);
dt.Columns.Add(column);
}
}
catch (Exception Ex)
{ }
}
for (int sheetindex = 0; sheetindex < workbook.NumberOfSheets; sheetindex++)
{
sheet = (XSSFSheet)workbook.GetSheetAt(sheetindex);
if (null != sheet)
{
// LastRowNum is the number of rows of current table
int rowCount = sheet.LastRowNum + 1;
//Reading Rows and Copying it to Data Table;
try
{
for (int i = (sheet.FirstRowNum + 1); i < rowCount; i++)
{
XSSFRow row = (XSSFRow)sheet.GetRow(i);
DataRow dataRow = dt.NewRow();
isBlanKRow = true;
try
{
for (int j = row.FirstCellNum; j < cellCount; j++)
{
if (null != row.GetCell(j) && !string.IsNullOrEmpty(row.GetCell(j).ToString()) && !string.IsNullOrWhiteSpace(row.GetCell(j).ToString()))
{
dataRow[j] = row.GetCell(j).ToString();
isBlanKRow = false;
}
}
}
catch (Exception Ex)
{ }
if (!isBlanKRow)
{
dt.Rows.Add(dataRow);
}
}
}
catch (Exception Ex)
{ }
}
}
}
catch (Exception Ex)
{ }
finally
{
workbook.UnlockStructure();
workbook.UnlockRevision();
workbook.UnlockWindows();
workbook = null;
sheet = null;
}
}
