Hi Team,
I used the NPOI to export a excel file from the asp.net mvc application. And all codes are ok. and export the excel file is ok. However, when I open the downloaded excel file, it will show the message "We found a problem with some content in "test.xlsx. Do you want to try to recover as much as we can? If you trust the source of this workbook, click Yes", if I click the "yes", the excel open and show the content, otherwise it will show nothing.
```
public enum ExcelType
{
Excel2003,
ExcelLatest
}
public class ExportExcelActionResult<T> : System.Web.Mvc.ActionResult
where T : class, IExcelDataViewModel
{
private IEnumerable<T> DataSource { get; set; }
private string FileName { get; set; }
private ExcelType ExcelType { get; set; }
public ExportExcelActionResult(IEnumerable<T> dataSource, string fileName, ExcelType excelType = ExcelType.ExcelLatest)
{
DataSource = dataSource;
FileName = fileName;
ExcelType = excelType;
}
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
var currentResponse = context.HttpContext.Response;
FileName = FileName + (ExcelType == ExcelType.ExcelLatest ? ".xlsx" : ".xls");
currentResponse.Clear();
var headerValue = ContentDispositionUtil.GetHeaderValue(FileName);
context.HttpContext.Response.AddHeader("Content-Disposition", headerValue);
currentResponse.Cache.SetCacheability(HttpCacheability.NoCache);
IWorkbook workbook;
if (ExcelType == ExcelType.ExcelLatest)
{
currentResponse.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
workbook = new XSSFWorkbook();
}
else
{
currentResponse.ContentType = "application/vnd.ms-excel";
workbook = new HSSFWorkbook();
}
ISheet sheet1 = workbook.CreateSheet("Sheet1");
//ISheet sheet2 = workbook.CreateSheet("Sheet2");
//workbook.SetSheetHidden(1, SheetState.VeryHidden);
var firstData = DataSource.FirstOrDefault();
var dataType = firstData != null ? firstData.GetType() : typeof(T);
var headerProperties = GetColumnProperties(dataType);
IRow headerRow = sheet1.CreateRow(0);
var headerColumnIndex = 0;
foreach (var propertyInfo in headerProperties)
{
var columnName =
propertyInfo.GetCustomAttribute(typeof(ColumnNameAttribute)) as ColumnNameAttribute;
if (columnName != null)
{
headerRow.CreateCell(headerColumnIndex).SetCellValue(columnName.HeaderName);
headerColumnIndex++;
}
sheet1.AutoSizeColumn(headerColumnIndex);
}
var rowIndex = 1;
foreach (var dataItem in DataSource)
{
IRow dataRow = sheet1.CreateRow(rowIndex);
var properties = GetColumnProperties(dataType);
var columnIndex = 0;
foreach (var propertyInfo in properties)
{
var propertyValue = propertyInfo.GetValue(dataItem);
var cell = dataRow.CreateCell(columnIndex);
if (propertyValue != null)
{
if (propertyInfo.PropertyType == typeof(long) || propertyInfo.PropertyType == typeof(int))
{
cell.SetCellType(CellType.Numeric);
cell.SetCellValue((long)propertyInfo.GetValue(dataItem));
}
else if (propertyInfo.PropertyType == typeof(DateTime))
{
cell.SetCellType(CellType.String);
cell.SetCellValue((DateTime)propertyInfo.GetValue(dataItem));
}
else if (propertyInfo.PropertyType == typeof(bool))
{
cell.SetCellType(CellType.Boolean);
cell.SetCellValue((bool)propertyInfo.GetValue(dataItem));
}
else
{
cell.SetCellType(CellType.Blank);
cell.SetCellValue(propertyInfo.GetValue(dataItem).ToString());
}
}
else
{
cell.SetCellType(CellType.Blank);
cell.SetCellValue(string.Empty);
}
sheet1.AutoSizeColumn(columnIndex);
columnIndex++;
}
rowIndex++;
}
workbook.Write(currentResponse.OutputStream);
currentResponse.End();
currentResponse.Flush();
currentResponse.Close();
}
#region Helper Methods
private List<PropertyInfo> GetColumnProperties(Type dataType)
{
return dataType.GetProperties().Where(
p => p.CanRead
&& p.CanWrite
&& p.GetCustomAttributes(typeof(ColumnNameAttribute), false).Any()
).ToList();
}
#endregion
internal static class ContentDispositionUtil
{
private const string HexDigits = "0123456789ABCDEF";
private static void AddByteToStringBuilder(byte b, StringBuilder builder)
{
builder.Append('%');
int i = b;
AddHexDigitToStringBuilder(i >> 4, builder);
AddHexDigitToStringBuilder(i % 16, builder);
}
private static void AddHexDigitToStringBuilder(int digit, StringBuilder builder)
{
builder.Append(HexDigits[digit]);
}
private static string CreateRfc2231HeaderValue(string filename)
{
StringBuilder builder = new StringBuilder("attachment; filename*=UTF-8''");
byte[] filenameBytes = Encoding.UTF8.GetBytes(filename);
foreach (byte b in filenameBytes)
{
if (IsByteValidHeaderValueCharacter(b))
{
builder.Append((char)b);
}
else
{
AddByteToStringBuilder(b, builder);
}
}
return builder.ToString();
}
public static string GetHeaderValue(string fileName)
{
// If fileName contains any Unicode characters, encode according
// to RFC 2231 (with clarifications from RFC 5987)
foreach (char c in fileName)
{
if ((int)c > 127)
{
return CreateRfc2231HeaderValue(fileName);
}
}
// Knowing there are no Unicode characters in this fileName, rely on
// ContentDisposition.ToString() to encode properly.
// In .Net 4.0, ContentDisposition.ToString() throws FormatException if
// the file name contains Unicode characters.
// In .Net 4.5, ContentDisposition.ToString() no longer throws FormatException
// if it contains Unicode, and it will not encode Unicode as we require here.
// The Unicode test above is identical to the 4.0 FormatException test,
// allowing this helper to give the same results in 4.0 and 4.5.
ContentDisposition disposition = new ContentDisposition() { FileName = fileName };
return disposition.ToString();
}
// Application of RFC 2231 Encoding to Hypertext Transfer Protocol (HTTP) Header Fields, sec. 3.2
// http://greenbytes.de/tech/webdav/draft-reschke-rfc2231-in-http-latest.html
private static bool IsByteValidHeaderValueCharacter(byte b)
{
if ((byte)'0' <= b && b <= (byte)
Comments: ** Comment from web user: lalitnbhatt **
I used the NPOI to export a excel file from the asp.net mvc application. And all codes are ok. and export the excel file is ok. However, when I open the downloaded excel file, it will show the message "We found a problem with some content in "test.xlsx. Do you want to try to recover as much as we can? If you trust the source of this workbook, click Yes", if I click the "yes", the excel open and show the content, otherwise it will show nothing.
```
public enum ExcelType
{
Excel2003,
ExcelLatest
}
public class ExportExcelActionResult<T> : System.Web.Mvc.ActionResult
where T : class, IExcelDataViewModel
{
private IEnumerable<T> DataSource { get; set; }
private string FileName { get; set; }
private ExcelType ExcelType { get; set; }
public ExportExcelActionResult(IEnumerable<T> dataSource, string fileName, ExcelType excelType = ExcelType.ExcelLatest)
{
DataSource = dataSource;
FileName = fileName;
ExcelType = excelType;
}
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
var currentResponse = context.HttpContext.Response;
FileName = FileName + (ExcelType == ExcelType.ExcelLatest ? ".xlsx" : ".xls");
currentResponse.Clear();
var headerValue = ContentDispositionUtil.GetHeaderValue(FileName);
context.HttpContext.Response.AddHeader("Content-Disposition", headerValue);
currentResponse.Cache.SetCacheability(HttpCacheability.NoCache);
IWorkbook workbook;
if (ExcelType == ExcelType.ExcelLatest)
{
currentResponse.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
workbook = new XSSFWorkbook();
}
else
{
currentResponse.ContentType = "application/vnd.ms-excel";
workbook = new HSSFWorkbook();
}
ISheet sheet1 = workbook.CreateSheet("Sheet1");
//ISheet sheet2 = workbook.CreateSheet("Sheet2");
//workbook.SetSheetHidden(1, SheetState.VeryHidden);
var firstData = DataSource.FirstOrDefault();
var dataType = firstData != null ? firstData.GetType() : typeof(T);
var headerProperties = GetColumnProperties(dataType);
IRow headerRow = sheet1.CreateRow(0);
var headerColumnIndex = 0;
foreach (var propertyInfo in headerProperties)
{
var columnName =
propertyInfo.GetCustomAttribute(typeof(ColumnNameAttribute)) as ColumnNameAttribute;
if (columnName != null)
{
headerRow.CreateCell(headerColumnIndex).SetCellValue(columnName.HeaderName);
headerColumnIndex++;
}
sheet1.AutoSizeColumn(headerColumnIndex);
}
var rowIndex = 1;
foreach (var dataItem in DataSource)
{
IRow dataRow = sheet1.CreateRow(rowIndex);
var properties = GetColumnProperties(dataType);
var columnIndex = 0;
foreach (var propertyInfo in properties)
{
var propertyValue = propertyInfo.GetValue(dataItem);
var cell = dataRow.CreateCell(columnIndex);
if (propertyValue != null)
{
if (propertyInfo.PropertyType == typeof(long) || propertyInfo.PropertyType == typeof(int))
{
cell.SetCellType(CellType.Numeric);
cell.SetCellValue((long)propertyInfo.GetValue(dataItem));
}
else if (propertyInfo.PropertyType == typeof(DateTime))
{
cell.SetCellType(CellType.String);
cell.SetCellValue((DateTime)propertyInfo.GetValue(dataItem));
}
else if (propertyInfo.PropertyType == typeof(bool))
{
cell.SetCellType(CellType.Boolean);
cell.SetCellValue((bool)propertyInfo.GetValue(dataItem));
}
else
{
cell.SetCellType(CellType.Blank);
cell.SetCellValue(propertyInfo.GetValue(dataItem).ToString());
}
}
else
{
cell.SetCellType(CellType.Blank);
cell.SetCellValue(string.Empty);
}
sheet1.AutoSizeColumn(columnIndex);
columnIndex++;
}
rowIndex++;
}
workbook.Write(currentResponse.OutputStream);
currentResponse.End();
currentResponse.Flush();
currentResponse.Close();
}
#region Helper Methods
private List<PropertyInfo> GetColumnProperties(Type dataType)
{
return dataType.GetProperties().Where(
p => p.CanRead
&& p.CanWrite
&& p.GetCustomAttributes(typeof(ColumnNameAttribute), false).Any()
).ToList();
}
#endregion
internal static class ContentDispositionUtil
{
private const string HexDigits = "0123456789ABCDEF";
private static void AddByteToStringBuilder(byte b, StringBuilder builder)
{
builder.Append('%');
int i = b;
AddHexDigitToStringBuilder(i >> 4, builder);
AddHexDigitToStringBuilder(i % 16, builder);
}
private static void AddHexDigitToStringBuilder(int digit, StringBuilder builder)
{
builder.Append(HexDigits[digit]);
}
private static string CreateRfc2231HeaderValue(string filename)
{
StringBuilder builder = new StringBuilder("attachment; filename*=UTF-8''");
byte[] filenameBytes = Encoding.UTF8.GetBytes(filename);
foreach (byte b in filenameBytes)
{
if (IsByteValidHeaderValueCharacter(b))
{
builder.Append((char)b);
}
else
{
AddByteToStringBuilder(b, builder);
}
}
return builder.ToString();
}
public static string GetHeaderValue(string fileName)
{
// If fileName contains any Unicode characters, encode according
// to RFC 2231 (with clarifications from RFC 5987)
foreach (char c in fileName)
{
if ((int)c > 127)
{
return CreateRfc2231HeaderValue(fileName);
}
}
// Knowing there are no Unicode characters in this fileName, rely on
// ContentDisposition.ToString() to encode properly.
// In .Net 4.0, ContentDisposition.ToString() throws FormatException if
// the file name contains Unicode characters.
// In .Net 4.5, ContentDisposition.ToString() no longer throws FormatException
// if it contains Unicode, and it will not encode Unicode as we require here.
// The Unicode test above is identical to the 4.0 FormatException test,
// allowing this helper to give the same results in 4.0 and 4.5.
ContentDisposition disposition = new ContentDisposition() { FileName = fileName };
return disposition.ToString();
}
// Application of RFC 2231 Encoding to Hypertext Transfer Protocol (HTTP) Header Fields, sec. 3.2
// http://greenbytes.de/tech/webdav/draft-reschke-rfc2231-in-http-latest.html
private static bool IsByteValidHeaderValueCharacter(byte b)
{
if ((byte)'0' <= b && b <= (byte)
Comments: ** Comment from web user: lalitnbhatt **
Hi tonyqus,
My issue is resolved.
One of our developers had incorrectly added something else as well in the response.
Thanks