- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我正在使用 EPPLUS 生成 Excel 文件……到目前为止,还不错。现在我必须生成相同的报告,但格式为 PDF。
有什么方法可以完成这个吗?最好,我想使用 Excel 文件本身,因为我用来提供 Excel 文件的数据集不完整...我执行一些 SQL 查询以获取缺少的字段...
这是我获取生成的 Excel 文件的方法:
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=RelatorioTempoMediano.xlsx");
Response.BinaryWrite(p.GetAsByteArray());
Response.End();
最佳答案
我找到了一个可能的解决方案。EPPlus 包的创建者有一个 PdfReport 库。
https://github.com/VahidN/EPPlus.Core/issues/8
在那里你可以看到图书馆。安装 pdfreport.core
我对代码进行了一些修改,以通过运行示例使其适应您的要求。
实用类
public class Utilities
{
public class ExcelDataReaderDataSource : IDataSource
{
private readonly string _filePath;
private readonly string _worksheet;
public ExcelDataReaderDataSource(string filePath, string worksheet)
{
_filePath = filePath;
_worksheet = worksheet;
}
public IEnumerable<IList<CellData>> Rows()
{
var fileInfo = new FileInfo(_filePath);
if (!fileInfo.Exists)
{
throw new FileNotFoundException($"{_filePath} file not found.");
}
using (var package = new ExcelPackage(fileInfo))
{
var worksheet = package.Workbook.Worksheets[_worksheet];
var startCell = worksheet.Dimension.Start;
var endCell = worksheet.Dimension.End;
for (var row = startCell.Row + 1; row < endCell.Row + 1; row++)
{
var i = 0;
var result = new List<CellData>();
for (var col = startCell.Column; col <= endCell.Column; col++)
{
var pdfCellData = new CellData
{
PropertyName = worksheet.Cells[1, col].Value.ToString(),
PropertyValue = worksheet.Cells[row, col].Value,
PropertyIndex = i++
};
result.Add(pdfCellData);
}
yield return result;
}
}
}
}
public static class ExcelUtils
{
public static IList<string> GetColumns(string filePath, string excelWorksheet)
{
var fileInfo = new FileInfo(filePath);
if (!fileInfo.Exists)
{
throw new FileNotFoundException($"{filePath} file not found.");
}
var columns = new List<string>();
using (var package = new ExcelPackage(fileInfo))
{
var worksheet = package.Workbook.Worksheets[excelWorksheet];
var startCell = worksheet.Dimension.Start;
var endCell = worksheet.Dimension.End;
for (int col = startCell.Column; col <= endCell.Column; col++)
{
var colHeader = worksheet.Cells[1, col].Value.ToString();
columns.Add(colHeader);
}
}
return columns;
}
}
public static IPdfReportData CreateExcelToPdfReport(string filePath, string excelWorksheet)
{
return new PdfReport().DocumentPreferences(doc =>
{
doc.RunDirection(PdfRunDirection.LeftToRight);
doc.Orientation(PageOrientation.Portrait);
doc.PageSize(PdfPageSize.A4);
doc.DocumentMetadata(new DocumentMetadata { Author = "Vahid", Application = "PdfRpt", Keywords = "Test", Subject = "Test Rpt", Title = "Test" });
doc.Compression(new CompressionSettings
{
EnableCompression = true,
EnableFullCompression = true
});
})
.DefaultFonts(fonts =>
{
fonts.Path(TestUtils.GetVerdanaFontPath(),
TestUtils.GetTahomaFontPath());
fonts.Size(9);
fonts.Color(System.Drawing.Color.Black);
})
.PagesFooter(footer =>
{
footer.DefaultFooter(DateTime.Now.ToString("MM/dd/yyyy"));
})
.PagesHeader(header =>
{
header.CacheHeader(cache: true); // It's a default setting to improve the performance.
header.DefaultHeader(defaultHeader =>
{
defaultHeader.RunDirection(PdfRunDirection.LeftToRight);
defaultHeader.ImagePath(TestUtils.GetImagePath("01.png"));
defaultHeader.Message("Excel To Pdf Report");
});
})
.MainTableTemplate(template =>
{
template.BasicTemplate(BasicTemplate.ClassicTemplate);
})
.MainTablePreferences(table =>
{
table.ColumnsWidthsType(TableColumnWidthType.Relative);
table.MultipleColumnsPerPage(new MultipleColumnsPerPage
{
ColumnsGap = 7,
ColumnsPerPage = 3,
ColumnsWidth = 170,
IsRightToLeft = false,
TopMargin = 7
});
})
.MainTableDataSource(dataSource =>
{
dataSource.CustomDataSource(() => new ExcelDataReaderDataSource(filePath, excelWorksheet));
})
.MainTableColumns(columns =>
{
columns.AddColumn(column =>
{
column.PropertyName("rowNo");
column.IsRowNumber(true);
column.CellsHorizontalAlignment(HorizontalAlignment.Center);
column.IsVisible(true);
column.Order(0);
column.Width(1);
column.HeaderCell("#");
});
var order = 1;
foreach (var columnInfo in ExcelUtils.GetColumns(filePath, excelWorksheet))
{
columns.AddColumn(column =>
{
column.PropertyName(columnInfo);
column.CellsHorizontalAlignment(HorizontalAlignment.Center);
column.IsVisible(true);
column.Order(order++);
column.Width(1);
column.HeaderCell(columnInfo);
});
}
})
.MainTableEvents(events =>
{
events.DataSourceIsEmpty(message: "There is no data available to display.");
})
.Generate(data => data.AsPdfFile(TestUtils.GetOutputFileName()));
}
}
TestUtils(修改后 GetBaseDir 抛出服务器映射路径)
public static class TestUtils
{
public static string GetBaseDir()
{
return HttpContext.Current.Server.MapPath("~/");
}
public static string GetImagePath(string fileName)
{
return Path.Combine(GetBaseDir(), "Images", fileName);
}
public static string GetDataFilePath(string fileName)
{
return Path.Combine(GetBaseDir(), "Data", fileName);
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static string GetOutputFileName([CallerMemberName] string methodName = null)
{
return Path.Combine(GetOutputFolder(), $"{methodName}.pdf");
}
public static string GetOutputFolder()
{
var dir = Path.Combine(GetBaseDir(), "App_Data", "out");
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
return dir;
}
public static string GetWingdingFontPath()
{
return Path.Combine(GetBaseDir(), "fonts", "wingding.ttf");
}
public static string GetTahomaFontPath()
{
return Path.Combine(GetBaseDir(), "fonts", "tahoma.ttf");
}
public static string GetVerdanaFontPath()
{
return Path.Combine(GetBaseDir(), "fonts", "verdana.ttf");
}
public static Font GetUnicodeFont(
string fontName, string fontFilePath, float size, int style, BaseColor color)
{
if (!FontFactory.IsRegistered(fontName))
{
FontFactory.Register(fontFilePath);
}
return FontFactory.GetFont(fontName, BaseFont.IDENTITY_H, BaseFont.EMBEDDED, size, style, color);
}
public static void VerifyPdfFileIsReadable(byte[] file)
{
PdfReader reader = null;
try
{
reader = new PdfReader(file);
var author = reader.Info["Author"] as string;
if (string.IsNullOrWhiteSpace(author) || !author.Equals("Vahid"))
{
throw new InvalidPdfException("This is not a valid PDF file.");
}
}
finally
{
reader?.Close();
}
}
public static void VerifyPdfFileIsReadable(string filePath)
{
VerifyPdfFileIsReadable(File.ReadAllBytes(filePath));
}
}
Controller 方法
public ActionResult DownloadFile()
{
var report = Utilities.Utilities.CreateExcelToPdfReport(
filePath: Server.MapPath("~/App_Data/Financial Sample.xlsx"),
excelWorksheet: "Sheet1");
Utilities.TestUtils.VerifyPdfFileIsReadable(report.FileName);
string filename = Path.GetFileName(report.FileName);
string filepath = report.FileName;
byte[] filedata = System.IO.File.ReadAllBytes(filepath);
string contentType = MimeMapping.GetMimeMapping(filepath);
var cd = new System.Net.Mime.ContentDisposition
{
FileName = filename,
Inline = true,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(filedata, contentType);
}
You will need to add the fonts and maybe images folder to your solution, so the utilites can find the required files.
关于c# - 从生成的 Excel 文件生成 PDF 报告(EPPLUS 库),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12512036/
是否可以在 EPPlus 中为整个列设置样式?我希望我可以只使用 Column方法,但是当我这样做时,我得到了奇怪的结果: //Sets all cells in all columns to Red
有人知道如何使用 EPPLUS 设置条件格式的字体颜色吗? Using rng = ws.Cells("A7:AD29") Dim condSumLn = ws.ConditionalForm
我正在查看 POST 以使用 EPPlus 在 Excel 中创建多级可折叠分组,但我无法在现有组中创建内部组。 请参阅我在这里使用的示例文件 看来,我需要为第 14-18 行设置 OutlineLe
示例。埃普拉斯怎么样? Sheet.Cells["a1:d1"].Column.Width = 10; 在 Excel 互操作中: Sheet.get_Range("a1", "d1").Column
我在使用 EPPlus 处理 Excel 文档中的注释时遇到了一些问题。我可以添加评论并删除它们,但有时它不成功。 我正在使用注释来显示 Excel 文件处理结果的验证消息,并且当该文件被重新处理时,
我正在将 SSRS 报告导出到单独的 excel 文件中,并使用 EPPlus 将它们合并到一个文件中。合并成功,但当我尝试在 Excel 中打开文件时出现以下错误。 我删除了报告数据以生成空报告,但
我正在使用EPPlus读取excel工作表并将数据加载到数据表中以执行进一步的操作,然后将修改后的数据保存回excel文件中。 下面的代码检查单元格值是否为浮点值,然后将浮点值转换为日期时间。 当单元
通过查看EPPlus随附的示例,我已经成功创建了数据透视表,但是我无法为其设置正确的报告布局。我希望它是“表格格式”,而不是“大纲”或其他格式。在我看来,EPPlus现在不支持此功能,但是也许我缺少了
我使用 EPPlus 阅读工作表。在此工作表中,我需要的数据在列 B-D 中.在栏目A有静态值,我会忽略。 col A 中的值填写到Row 1000 .但是,我需要的数据只会在那里,例如 Row 45
在 EPPlus 中,我可以使用 workSheet.Cells[x, y].AddComment() 将注释添加到工作表中的单元格 但是如何从给定单元格中删除注释 - 没有 workSheet.Ce
设置列的 WrapText=true 后,我想查看行的新高度(即文本是否换行,行数)。行的 Height 属性似乎未更新。 ExcelPackage pkg = new ExcelPa
我目前正在与一位在 Excel 中手动生成发票的客户合作。我已经使用 epplus 自动为他们生成这个文件。 我的要求之一是每个页面周围都应该有一个边框,并以大约 7 行长的标题开始(并且每行具有不同
更改单元格的值时遇到问题。这是我的代码: FileInfo newFile = new FileInfo(file); ExcelPackage pck = new ExcelPackage(newF
当我使用 EPPlus 自动调整格式化为日期字符串的列时,自动调整机制使用未格式化的字符串作为列宽度的度量。 这是一个错误还是我做错了什么? 代码 sheet.Column(2).Style.Numb
using (var pck = new ExcelPackage(new FileInfo(wb_path))) { ExcelWorksheet ws = pck.Workbook.Wor
我有以下代码行,它根据特定列对工作表中的数据进行升序排序。问题是,它考虑了第一行(单元格 A1、B1 等)。 worksheet.Cells["A:AA"].Sort(new int[] { 5, 1
我正在.NET 4.0 命令行应用程序上使用 EPPlus 库创建电子表格。 我成功地从数据库中加载了所有数据,最后我正在创建一个图形,这是我的代码: var chart = sheet.Drawin
如何使用 EPPLus 将图表创建为单独的工作表,而不是作为现有工作表中的绘图? 最佳答案 在 4.0.4.0 版本(从 codeplex 下载代码,以纠正保存文件中的错误),您可以使用: workb
我正在运行一个带有 EPPlus 库的 C# 项目,我需要它检查各个列/行中的数据的单元格,然后找到“关键字”,可以说并将其与其他各个列/行中的数据匹配。 我需要知道一种将一个单元格中的数据与另一个单
我在使用 C# 和 EPPlus 从工作簿中读取某些工作表时遇到问题。 错误信息 name contains invalid characters 即使多次检查工作簿中的工作表名称、文件名和列标题以确
我是一名优秀的程序员,十分优秀!