我已经使用EPPLUS将我的gridview数据导出到excel,但是对于几列我有这个绿色标记" Number Stored as Text"打开导出的excel文件后出现提示。
如何在导出到excel代码中编码以更改数据类型/从指定列的第2行开始转换为特定列的数字,因为第1行是标题?
答案 0 :(得分:2)
我有类似的问题。正如Ordel Eraki所说:不要将值字符串化:
workSheet.Cells[1, 1].Value = 2; // Value is object
workSheet.Cells [1,1] .Value = 2.ToString()
答案 1 :(得分:1)
您应该将字符串保存为int
而不是string
。每当您希望您的单元格为数字时,只需将您的单元格输入转换为int
。
这意味着,在填充数据时,请务必将其填充为int
。
答案 2 :(得分:1)
我在这里更新了你的代码。
检查添加的代码..
的 EDITED 强>
我已更改DataTable
的变量名称,假定您正在执行的操作.. GridView1
是GridView UI Control
,您将DataTable Name
设为GridView1
,代码可能会混淆GridView1
protected void EXPORT_BUTTON_Click(object sender, EventArgs e)
{
// Added Code
int parseValue;
bool isInt;
ExcelPackage package = new ExcelPackage();
ExcelWorksheet Grid = package.Workbook.Worksheets.Add("ORSA ASSESSMENTS");
DataTable dt = new DataTable();
for (int i = 0; i < dt.Columns.Count; i++)
{
// Update Type
dt.Columns.Add("column" + i.ToString(), typeof(int));
}
foreach (GridViewRow row in GridView1.Rows)
{
DataRow dr = dt.NewRow();
for (int j = 0; j < GridView1.Columns.Count; j++)
{
row.Cells[j].Text = row.Cells[j].Text.Replace(" ", " ");
// Added Code
isInt = int.TryParse(row.Cells[j].Text.Trim(), out parseValue);
// Added Code
if (isInt)
dr["column" + j.ToString()] = parseValue;
}
dt.Rows.Add(dr);
}
Grid.Cells["A1"].LoadFromDataTable(dt, true);
using (ExcelRange rng = Grid.Cells["A1:Z1"])
{
rng.Style.Font.Bold = true;
}
Grid.Cells[ORSA.Dimension.Address].AutoFitColumns();
var FolderPath = ServerName + DirectoryLocation + DirectoryFolder + ExportsFolder;
var filename = ExcelName + @"_" + ".xlsx";
var filepath = new FileInfo(Path.Combine(FolderPath, filename));
Response.Clear();
package.SaveAs(filepath);
Response.AddHeader("content-disposition", "attachment; filename=" + filename + ";");
Response.Charset = "";
Response.ContentType = "application/vnd.xlsx";
Response.TransmitFile(filepath.FullName);
Response.End();
}
这是我模拟的样本,是一个有效的例子
protected void Page_Load(object sender, EventArgs e)
{
// Check
if (!IsPostBack)
{
DataTable dt = new DataTable();
// Create Column
for(int i = 0; i < 5; i++)
dt.Columns.Add("column" + i, typeof(int));
for (int i = 0; i < 10; i++)
dt.Rows.Add(i, i+1, i+2, i+3, i+4);
GenerateExcel(dt);
}
}
private void GenerateExcel(DataTable dt)
{
using (ExcelPackage pkg = new ExcelPackage())
{
ExcelWorksheet ws = pkg.Workbook.Worksheets.Add("Sheet1");
ws.Cells[1, 1].LoadFromDataTable(dt, true, OfficeOpenXml.Table.TableStyles.Light18);
pkg.SaveAs(new FileInfo("C:\\Test.xlsx"));
}
}